python实现百度关键词排名查询


Posted in Python onMarch 30, 2014

就是一个简单的python查询百度关键词排名的函数,以下是一些简介:
1、UA随机
2、操作简单方便,直接getRank(关键词,域名)就可以了
3、编码转化。编码方面应该没啥问题了。
4、结果丰富。不仅有排名,还有搜索结果的title,URL,快照时间,符合SEO需求
5、拿来做个软件或者自己用都很方便。

功能是单线程实现,速度慢,大家可以参考修改成自己需要的。

#coding=utf-8
import requests
import BeautifulSoup
import re
import random
def decodeAnyWord(w):
    try:
        w.decode('utf-8')
    except:
        w = w.decode('gb2312')
    else:
        w = w.decode('utf-8')
    return w
def createURL(checkWord):   #create baidu URL with search words
    checkWord = checkWord.strip()
    checkWord = checkWord.replace(' ', '+').replace('\n', '')
    baiduURL = 'http://www.baidu.com/s?wd=%s&rn=100' % checkWord
    return baiduURL
def getContent(baiduURL):   #get the content of the serp
    uaList = ['Mozilla/4.0+(compatible;+MSIE+6.0;+Windows+NT+5.1;+SV1;+.NET+CLR+1.1.4322;+TencentTraveler)',
    'Mozilla/4.0+(compatible;+MSIE+6.0;+Windows+NT+5.1;+SV1;+.NET+CLR+2.0.50727;+.NET+CLR+3.0.4506.2152;+.NET+CLR+3.5.30729)',
    'Mozilla/5.0+(Windows+NT+5.1)+AppleWebKit/537.1+(KHTML,+like+Gecko)+Chrome/21.0.1180.89+Safari/537.1',
    'Mozilla/4.0+(compatible;+MSIE+6.0;+Windows+NT+5.1;+SV1)',
    'Mozilla/5.0+(Windows+NT+6.1;+rv:11.0)+Gecko/20100101+Firefox/11.0',
    'Mozilla/4.0+(compatible;+MSIE+8.0;+Windows+NT+5.1;+Trident/4.0;+SV1)',
    'Mozilla/4.0+(compatible;+MSIE+8.0;+Windows+NT+5.1;+Trident/4.0;+GTB7.1;+.NET+CLR+2.0.50727)',
    'Mozilla/4.0+(compatible;+MSIE+8.0;+Windows+NT+5.1;+Trident/4.0;+KB974489)']
    headers = {'User-Agent': random.choice(uaList)}
    r = requests.get(baiduURL, headers = headers)
    return r.content
def getLastURL(rawurl): #get final URL while there're redirects
    r = requests.get(rawurl)
    return r.url
def getAtext(atext):    #get the text with <a> and </a>
    pat = re.compile(r'<a .*?>(.*?)</a>')
    match = pat.findall(atext.replace('\n', ''))
    pureText = match[0].replace('<em>', '').replace('</em>', '')
    return pureText.replace('\n', '')
def getCacheDate(t):    #get the date of cache
    pat = re.compile(r'<span class="g">.*?(\d{4}-\d{1,2}-\d{1,2}) </span>')
    match = pat.findall(t)
    cacheDate = match[0]
    return cacheDate
def getRank(checkWord, domain): #main line
    checkWord = checkWord.replace('\n', '')
    checkWord = decodeAnyWord(checkWord)
    baiduURL = createURL(checkWord)
    cont = getContent(baiduURL)
    soup = BeautifulSoup.BeautifulSoup(cont)
    results = soup.findAll('table', {'class': 'result'})    #find all results in this page
    for result in results:
        checkData = unicode(result.find('span', {'class': 'g'}))
        if re.compile(r'^[^/]*%s.*?' %domain).match(checkData.replace('<b>', '').replace('</b>', '')): #改正则
            nowRank = result['id']  #get the rank if match the domain info
            resLink = result.find('h3').a
            resURL = resLink['href']
            domainURL = getLastURL(resURL)  #get the target URL
            resTitle = getAtext(unicode(resLink))   #get the title of the target page
            rescache = result.find('span', {'class': 'g'})
            cacheDate = getCacheDate(unicode(rescache)) #get the cache date of the target page
            res = u'%s, 第%s名, %s, %s, %s' % (checkWord, nowRank, resTitle, cacheDate, domainURL)
            return res.encode('gb2312')
            break
    else:
        return '>100'

domain = 'www.baidu.com' #set the domain which you want to search.
print getRank('百度', domain)
Python 相关文章推荐
python实现sublime3的less编译插件示例
Apr 27 Python
在Python的Django框架中创建语言文件
Jul 27 Python
Python环境下搭建属于自己的pip源的教程
May 05 Python
Python3 获取一大段文本之间两个关键字之间的内容方法
Oct 11 Python
详解配置Django的Celery异步之路踩坑
Nov 25 Python
python实现图片识别汽车功能
Nov 30 Python
Python + Requests + Unittest接口自动化测试实例分析
Dec 12 Python
PyTorch加载自己的数据集实例详解
Mar 18 Python
Python restful框架接口开发实现
Apr 13 Python
python让函数不返回结果的方法
Jun 22 Python
python 动态渲染 mysql 配置文件的示例
Nov 20 Python
python opencv肤色检测的实现示例
Dec 21 Python
python获取网页状态码示例
Mar 30 #Python
python单线程实现多个定时器示例
Mar 30 #Python
python实现猜数字游戏(无重复数字)示例分享
Mar 29 #Python
使用python实现扫描端口示例
Mar 29 #Python
Python Trie树实现字典排序
Mar 28 #Python
python实现探测socket和web服务示例
Mar 28 #Python
python实现目录树生成示例
Mar 28 #Python
You might like
浅谈Windows下 PHP4.0与oracle 8的连接设置
2006/10/09 PHP
Codeigniter实现发送带附件的邮件
2015/03/19 PHP
PHP7 新特性详细介绍
2016/09/06 PHP
thinkPHP5.0框架引入Traits功能实例分析
2017/03/18 PHP
DEFER怎么用?
2006/07/01 Javascript
Some tips of wmi scripting in jscript (1)
2007/04/03 Javascript
Javascript学习笔记二 之 变量
2010/12/15 Javascript
jquery ready函数、css函数及text()使用示例
2013/09/27 Javascript
Extjs4实现两个GridPanel之间数据拖拽功能具体方法
2013/11/21 Javascript
5种处理js跨域问题方法汇总
2014/12/04 Javascript
不得不分享的JavaScript常用方法函数集(下)
2015/12/25 Javascript
JS随机洗牌算法之数组随机排序
2016/03/23 Javascript
详解Javascript函数声明与递归调用
2016/10/22 Javascript
Javascript 制作图形验证码实例详解
2016/12/22 Javascript
javascript 删除数组元素和清空数组的简单方法
2017/02/24 Javascript
关于js对textarea换行符的处理方法浅析
2018/08/03 Javascript
新手入门js闭包学习过程解析
2019/10/08 Javascript
JQuery样式与属性设置方法分析
2019/12/07 jQuery
JavaScript实现留言板案例
2020/03/17 Javascript
vue界面发送表情的实现代码
2020/09/11 Javascript
[03:55]TI9战队采访——TNC Predator
2019/08/22 DOTA
python实现搜索本地文件信息写入文件的方法
2016/02/22 Python
python TF-IDF算法实现文本关键词提取
2019/05/29 Python
10个顶级Python实用库推荐
2021/03/04 Python
文员的职业生涯规划发展方向
2014/02/08 职场文书
《燕子专列》教学反思
2014/02/21 职场文书
大学生应聘求职信
2014/05/26 职场文书
离职报告格式
2014/11/04 职场文书
接待员岗位职责
2015/02/13 职场文书
2015年安全生产工作总结范文
2015/04/02 职场文书
家长意见书
2015/06/04 职场文书
死亡诗社观后感
2015/06/05 职场文书
2015年国庆放假通知范文
2015/08/18 职场文书
2016年领导干部廉政承诺书
2016/03/24 职场文书
Java实现聊天机器人完善版
2021/07/04 Java/Android
SpringBoot2零基础到精通之数据库专项精讲
2022/03/22 Java/Android