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保存MongoDB上的文件到本地的方法
Mar 16 Python
python 捕获shell脚本的输出结果实例
Jan 04 Python
利用标准库fractions模块让Python支持分数类型的方法详解
Aug 11 Python
浅谈Python2获取中文文件名的编码问题
Jan 09 Python
TensorFlow深度学习之卷积神经网络CNN
Mar 09 Python
Windows 7下Python Web环境搭建图文教程
Mar 20 Python
python执行CMD指令,并获取返回的方法
Dec 19 Python
pandas数据筛选和csv操作的实现方法
Jul 02 Python
Keras使用tensorboard显示训练过程的实例
Feb 15 Python
基于Numba提高python运行效率过程解析
Mar 02 Python
如何基于Python按行合并两个txt
Nov 03 Python
Python&Matlab实现樱花的绘制
Apr 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
一棵php的类树(支持无限分类)
2006/10/09 PHP
php error_log 函数的使用
2009/04/13 PHP
深入理解:单一入口、MVC、ORM、CURD、ActiveRecord概念
2013/06/06 PHP
用php简单实现加减乘除计算器
2014/01/06 PHP
Zend Framework框架Smarty扩展实现方法
2016/03/22 PHP
ThinkPHP3.1.x修改成功与失败跳转页面的方法
2017/09/29 PHP
索趣科技的答案
2007/02/07 Javascript
数组方法解决JS字符串连接性能问题有争议
2011/01/12 Javascript
jQuery链式操作如何实现以及为什么要用链式操作
2013/01/17 Javascript
js动态拼接正则表达式的两种方法
2014/03/04 Javascript
jQuery子属性过滤选择器用法分析
2015/02/10 Javascript
JS烟花背景效果实现方法
2015/03/03 Javascript
基于BootStrap Metronic开发框架经验小结【六】对话框及提示框的处理和优化
2016/05/12 Javascript
JS组件系列之使用HTML标签的data属性初始化JS组件
2016/09/14 Javascript
JS基于面向对象实现的多个倒计时器功能示例
2017/02/28 Javascript
ionic 3.0+ 项目搭建运行环境的教程
2017/08/09 Javascript
自定义vue组件发布到npm的方法
2018/05/09 Javascript
使用vue根据状态添加列表数据和删除列表数据的实例
2018/09/29 Javascript
Vue.js 中的实用工具方法【推荐】
2019/07/04 Javascript
Python urlopen()函数 示例分享
2014/06/12 Python
Python手机号码归属地查询代码
2016/05/04 Python
使用XML库的方式,实现RPC通信的方法(推荐)
2017/06/14 Python
python技能之数据导出excel的实例代码
2017/08/11 Python
python利用JMeter测试Tornado的多线程
2020/01/12 Python
python爬虫请求头的使用
2020/12/01 Python
MoviePy常用剪辑类及Python视频剪辑自动化
2020/12/18 Python
css3 transform属性详解
2014/09/30 HTML / CSS
HTML5地理定位与第三方工具百度地图的应用
2016/11/17 HTML / CSS
mysql_pconnect()和mysql_connect()有什么区别
2012/05/25 面试题
学生党员思想汇报范文
2014/01/09 职场文书
《晚上的太阳》教学反思
2014/04/23 职场文书
清明节网上祭英烈活动总结
2014/04/30 职场文书
经典禁毒标语
2014/06/16 职场文书
五好文明家庭事迹材料
2014/12/20 职场文书
学校推普周活动总结
2015/05/07 职场文书
2016年学校党支部公开承诺书
2016/03/25 职场文书