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 相关文章推荐
pycharm 使用心得(九)解决No Python interpreter selected的问题
Jun 06 Python
Python标准库os.path包、glob包使用实例
Nov 25 Python
编写Python爬虫抓取暴走漫画上gif图片的实例分享
Apr 20 Python
python中模块查找的原理与方法详解
Aug 11 Python
Python3自动签到 定时任务 判断节假日的实例
Nov 13 Python
python图像和办公文档处理总结
May 28 Python
opencv-python 提取sift特征并匹配的实例
Dec 09 Python
pytorch 实现模型不同层设置不同的学习率方式
Jan 06 Python
解决Python3.7.0 SSL低版本导致Pip无法使用问题
Sep 03 Python
解决python3安装pandas出错的问题
May 20 Python
Python 如何解决稀疏矩阵运算
May 26 Python
分享python函数常见关键字
Apr 26 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 抽象方法与抽象类abstract关键字介绍及应用
2014/10/16 PHP
php猴子选大王问题解决方法
2015/05/12 PHP
php使用gd2绘制基本图形示例(直线、圆、正方形)
2017/02/15 PHP
select组合框option的捕捉实例代码
2008/09/30 Javascript
JavaScript的strict模式与with关键字介绍
2014/02/08 Javascript
基于JavaScript实现快速转换文本语言(繁体中文和简体中文)
2016/03/07 Javascript
js判断iframe中元素是否存在的实现代码
2016/12/24 Javascript
基于 webpack2 实现的多入口项目脚手架详解
2017/06/26 Javascript
vue引入swiper插件的使用实例
2017/07/19 Javascript
微信小程序使用request网络请求操作实例
2017/12/15 Javascript
Vue对象赋值视图不更新问题及解决方法
2019/06/03 Javascript
浅谈vuex的基本用法和mapaction传值问题
2019/11/08 Javascript
Vue使用JSEncrypt实现rsa加密及挂载方法
2020/02/07 Javascript
js绘制一条直线并旋转45度
2020/08/21 Javascript
关于javascript中的promise的用法和注意事项(推荐)
2021/01/15 Javascript
python写xml文件的操作实例
2014/10/05 Python
Python判断两个对象相等的原理
2017/12/12 Python
浅谈python可视化包Bokeh
2018/02/07 Python
基于pandas数据样本行列选取的方法
2018/04/20 Python
使用pandas的DataFrame的plot方法绘制图像的实例
2018/05/24 Python
python 读取目录下csv文件并绘制曲线v111的方法
2018/07/06 Python
Python实现的ftp服务器功能详解【附源码下载】
2019/06/26 Python
提升Python效率之使用循环机制代替递归函数
2019/07/23 Python
Python使用docx模块实现刷题功能代码
2020/02/13 Python
python编程进阶之类和对象用法实例分析
2020/02/21 Python
python dict乱码如何解决
2020/06/07 Python
利用Python中的Xpath实现一个在线汇率转换器
2020/09/09 Python
实例教程 一款纯css3实现的数字统计游戏
2014/11/10 HTML / CSS
C语言笔试集
2012/07/24 面试题
vue项目实现分页效果
2021/03/24 Vue.js
计算机应用应届生求职信
2014/07/12 职场文书
办理护照工作证明
2014/10/10 职场文书
2016年119消防宣传日活动总结
2016/04/05 职场文书
Go 自定义package包设置与导入操作
2021/05/06 Golang
Python实现简单的猜单词
2021/06/15 Python
Redis keys命令的具体使用
2022/06/05 Redis