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 Django模板的使用方法(图文)
Nov 04 Python
利用Python脚本在Nginx和uwsgi上部署MoinMoin的教程
May 05 Python
Python获取某一天是星期几的方法示例
Jan 17 Python
Python获取本机所有网卡ip,掩码和广播地址实例代码
Jan 22 Python
Python+request+unittest实现接口测试框架集成实例
Mar 16 Python
Python 等分切分数据及规则命名的实例代码
Aug 16 Python
Python函数的返回值、匿名函数lambda、filter函数、map函数、reduce函数用法实例分析
Dec 26 Python
python机器学习库xgboost的使用
Jan 20 Python
tensorflow ckpt模型和pb模型获取节点名称,及ckpt转pb模型实例
Jan 21 Python
Tensorflow tf.tile()的用法实例分析
May 22 Python
Tensorflow tensor 数学运算和逻辑运算方式
Jun 30 Python
pytorch 实现变分自动编码器的操作
May 24 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
PHP 八种基本的数据类型小结
2011/06/01 PHP
通过PHP的内置函数,通过DES算法对数据加密和解密
2012/06/21 PHP
PHP实现下载功能的代码
2012/09/29 PHP
PHP互换两个变量值的方法(不用第三变量)
2016/11/14 PHP
jquery offset函数应用实例
2012/11/14 Javascript
纯js网页画板(Graphics)类简介及实现代码
2012/12/24 Javascript
JQuery EasyUI 数字格式化处理示例
2014/05/05 Javascript
js与css实现弹出层覆盖整个页面的方法
2014/12/13 Javascript
jQuery事件绑定与解除绑定实现方法
2015/04/15 Javascript
JavaScript中解析JSON数据的三种方法
2015/07/03 Javascript
Bootstrap每天必学之基础排版
2015/11/20 Javascript
Ionic3 UI组件之Gallery Modal详解
2017/06/07 Javascript
bootstrap多层模态框滚动条消失的问题
2017/07/21 Javascript
微信小程序将字符串生成二维码图片的操作方法
2018/07/17 Javascript
Vue中的transition封装组件的实现方法
2019/08/13 Javascript
详解Vue中CSS样式穿透问题
2019/09/12 Javascript
Python模块包中__init__.py文件功能分析
2016/06/14 Python
Python文件操作之合并文本文件内容示例代码
2017/09/19 Python
python中的字符串内部换行方法
2018/07/19 Python
关于不懂Chromedriver如何配置环境变量问题解决方法
2019/06/12 Python
Python如何筛选序列中的元素的方法实现
2019/07/15 Python
在pycharm中配置Anaconda以及pip源配置详解
2019/09/09 Python
Python实现线性插值和三次样条插值的示例代码
2019/11/13 Python
Python Django搭建网站流程图解
2020/06/13 Python
CSS3 重置iphone浏览器按钮input,select等表单元素的默认样式
2014/10/11 HTML / CSS
html5自动播放mov格式视频的实例代码
2020/01/14 HTML / CSS
南威尔士家居商店:Leekes
2016/10/25 全球购物
Trina Turk官网:美国时装和泳装品牌
2018/06/10 全球购物
新西兰最大、占有率最高的综合性药房:PharmacyDirect药房中文网
2020/11/03 全球购物
高二历史教学反思
2014/01/25 职场文书
争做文明公民倡议书
2014/08/29 职场文书
高中军训感想
2015/08/07 职场文书
Mysql基础之常见函数
2021/04/22 MySQL
Python中的套接字编程是什么?
2021/06/21 Python
如何利用Python实现一个论文降重工具
2021/07/09 Python
Go语言实现一个简单的并发聊天室的项目实战
2022/03/18 Golang