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 正则式使用心得
May 07 Python
浅谈Python中数据解析
May 05 Python
python使用正则表达式替换匹配成功的组
Nov 17 Python
Python解决八皇后问题示例
Apr 22 Python
python Web开发你要理解的WSGI &amp; uwsgi详解
Aug 01 Python
Python-Flask:动态创建表的示例详解
Nov 22 Python
使用python动态生成波形曲线的实现
Dec 04 Python
Tensorflow的常用矩阵生成方式
Jan 04 Python
python中元组的用法整理
Jun 15 Python
浅谈django框架集成swagger以及自定义参数问题
Jul 07 Python
sublime3之内网安装python插件Anaconda的流程
Nov 10 Python
python通过opencv调用摄像头操作实例分析
Jun 07 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
DedeCMS 核心类TypeLink.class.php摘要笔记
2010/04/07 PHP
FireFox浏览器使用Javascript上传大文件
2013/10/30 PHP
php环境下利用session防止页面重复刷新的具体实现
2014/01/09 PHP
Zend Framework分发器用法示例
2016/12/11 PHP
实例讲解php将字符串输出到HTML
2019/01/27 PHP
PHP 8新特性简介
2020/08/18 PHP
jquery 关键字“拖曳搜索”之“拖曳”以及 图片“提示自适应放大”效果 的实现
2010/04/18 Javascript
jquery可见性过滤选择器使用示例
2013/06/24 Javascript
枚举的实现求得1-1000所有出现1的数字并计算出现1的个数
2013/09/10 Javascript
nodejs实现黑名单中间件设计
2014/06/17 NodeJs
javascript定义变量时带var与不带var的区别分析
2015/01/12 Javascript
PHP 数组current和next用法分享
2015/03/05 Javascript
基于ajax实现文件上传并显示进度条
2015/08/03 Javascript
JS实现的左侧竖向滑动菜单效果代码
2015/10/19 Javascript
JS组件Bootstrap Table使用方法详解
2016/02/02 Javascript
详解基于 Node.js 的轻量级云函数功能实现
2019/07/08 Javascript
微信小程序实现组件顶端固定或底端固定效果(不随滚动而滚动)
2020/04/09 Javascript
vue 遮罩层阻止默认滚动事件操作
2020/07/28 Javascript
vscode+gulp轻松开发小程序的完整步骤
2020/10/18 Javascript
解决ant design vue 表格a-table二次封装,slots渲染的问题
2020/10/28 Javascript
[02:54]辉夜杯主赛事第二日败者组 iG.V赛后采访
2015/12/26 DOTA
[01:59][TI9趣味视频] 全明星赛奖励
2019/08/23 DOTA
Python结巴中文分词工具使用过程中遇到的问题及解决方法
2017/04/15 Python
将Pytorch模型从CPU转换成GPU的实现方法
2019/08/19 Python
对pytorch中的梯度更新方法详解
2019/08/20 Python
解决pycharm中导入自己写的.py函数出错问题
2020/02/12 Python
keras .h5转移动端的.tflite文件实现方式
2020/05/25 Python
Easy Spirit官网:美国休闲鞋履中的代表品牌
2019/04/12 全球购物
瑞典多品牌连锁店:Johnells
2021/01/13 全球购物
幼儿园安全责任书
2014/04/14 职场文书
奠基仪式策划方案
2014/05/15 职场文书
学校校庆演讲稿
2014/05/22 职场文书
副主任竞聘演讲稿
2014/08/18 职场文书
营销总经理岗位职责范本
2014/09/02 职场文书
2015年五一劳动节演讲稿
2015/03/18 职场文书
Redis高级数据类型Hyperloglog、Bitmap的使用
2021/05/24 Redis