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网络编程学习笔记(六):Web客户端访问
Jun 09 Python
简单的Python抓taobao图片爬虫
Oct 26 Python
go语言计算两个时间的时间差方法
Mar 13 Python
python实现颜色rgb和hex相互转换的函数
Mar 19 Python
在Python中进行自动化单元测试的教程
Apr 15 Python
在python中pandas的series合并方法
Nov 12 Python
Python多线程同步---文件读写控制方法
Feb 12 Python
Python 的AES加密与解密实现
Jul 09 Python
python脚本之一键移动自定格式文件方法实例
Sep 02 Python
wxPython实现分隔窗口
Nov 19 Python
python3中sorted函数里cmp参数改变详解
Mar 12 Python
Python合并pdf文件的工具
Jul 01 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 Squid中可缓存的动态网页设计
2008/09/17 PHP
PHP导出MySQL数据到Excel文件(fputcsv)
2011/07/03 PHP
php实现的发送带附件邮件类实例
2014/09/22 PHP
php实现多城市切换特效
2015/08/09 PHP
php数据访问之查询关键字
2016/05/09 PHP
javascript 最常用的10个自定义函数[推荐]
2009/12/26 Javascript
20款超赞的jQuery插件 Web开发人员必备
2011/02/26 Javascript
Javascript this 的一些学习总结
2012/08/02 Javascript
JS下载文件|无刷新下载文件示例代码
2014/04/17 Javascript
jQuery实现返回顶部功能适合不支持js的浏览器
2014/08/19 Javascript
JS实现5秒钟自动封锁div层的方法
2015/02/20 Javascript
jQuery实现列表的全选功能
2015/03/18 Javascript
js实现异步循环实现代码
2016/02/16 Javascript
JavaScript开发者必备的10个Sublime Text插件
2016/02/27 Javascript
Javascript基础_简单比较undefined和null 值
2016/06/14 Javascript
json实现添加、遍历与删除属性的方法
2016/06/17 Javascript
巧用jQuery选择器提高写表单效率的方法
2016/08/19 Javascript
AngularJs表单校验功能实例代码
2017/02/09 Javascript
微信小程序局部刷新触发整页刷新效果的实现代码
2018/11/21 Javascript
JavaScript遍历查找数组中最大值与最小值的方法示例
2019/05/24 Javascript
JavaScript实现图片上传并预览并提交ajax
2019/09/30 Javascript
Jquery属性的获取/设置及样式添加/删除操作技巧分析
2019/12/23 jQuery
viewer.js实现图片预览功能
2020/06/24 Javascript
Python实现扩展内置类型的方法分析
2017/10/16 Python
Python中最大最小赋值小技巧(分享)
2017/12/23 Python
pycharm 批量修改变量名称的方法
2019/08/01 Python
Python学习笔记之While循环用法分析
2019/08/14 Python
使用Python快速打开一个百万行级别的超大Excel文件的方法
2021/03/02 Python
Boutique 1美国:阿联酋奢侈时尚零售商
2017/10/16 全球购物
幼儿园家长评语大全
2014/04/16 职场文书
员工考核评语大全
2014/04/26 职场文书
软环境建设心得体会
2014/09/09 职场文书
办公室文员岗位职责
2015/02/04 职场文书
安阳殷墟导游词
2015/02/10 职场文书
利用 SQL Server 过滤索引提高查询语句的性能分析
2021/07/15 SQL Server
关于@OnetoMany关系映射的排序问题,使用注解@OrderBy
2021/12/06 Java/Android