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中的序列化与反序列化的使用
Jun 30 Python
举例讲解Django中数据模型访问外键值的方法
Jul 21 Python
解决安装pycharm后不能执行python脚本的问题
Jan 19 Python
Python如何爬取微信公众号文章和评论(基于 Fiddler 抓包分析)
Jun 28 Python
Python图像处理模块ndimage用法实例分析
Sep 05 Python
python实现图片插入文字
Nov 26 Python
Python计算机视觉里的IOU计算实例
Jan 17 Python
Python 窗体(tkinter)下拉列表框(Combobox)实例
Mar 04 Python
idea2020手动安装python插件的实现方法
Jul 17 Python
解决selenium+Headless Chrome实现不弹出浏览器自动化登录的问题
Jan 09 Python
python爬虫利用代理池更换IP的方法步骤
Feb 21 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错误提示failed to open stream: HTTP request failed!的完美解决方法
2011/06/06 PHP
PHP curl 并发最佳实践代码分享
2012/09/05 PHP
PHP内核探索:变量概述
2014/01/30 PHP
php解决约瑟夫环示例
2014/04/09 PHP
php使用标签替换的方式生成静态页面
2015/05/21 PHP
PHP设计模式之工厂模式定义与用法详解
2018/04/03 PHP
关于火狐(firefox)及ie下event获取的两种方法
2012/12/27 Javascript
点击按钮或链接不跳转只刷新页面的脚本整理
2013/10/22 Javascript
iframe窗口高度自适应的又一个巧妙实现思路
2014/04/04 Javascript
JS基于cookie实现来宾统计记录访客信息的方法
2015/08/04 Javascript
JS查找字符串中出现次数最多的字符
2016/09/05 Javascript
深入理解AngularJS中的ng-bind-html指令和$sce服务
2016/09/08 Javascript
使用jquery datatable和bootsrap创建表格实例代码
2017/03/17 Javascript
Material(包括Material Icon)在Angular2中的使用详解
2018/02/11 Javascript
nodejs中用npm初始化来创建package.json的实例讲解
2018/10/10 NodeJs
[02:02]特效爆炸!DOTA2珍宝之瓶待你开启
2018/08/21 DOTA
[00:52]玛尔斯技能全介绍
2019/03/06 DOTA
Python实现可设置持续运行时间、线程数及时间间隔的多线程异步post请求功能
2018/01/11 Python
详解重置Django migration的常见方式
2019/02/15 Python
Python中变量的输入输出实例代码详解
2019/07/28 Python
python利用dlib获取人脸的68个landmark
2019/11/27 Python
python如何基于redis实现ip代理池
2020/01/17 Python
python网络编程:socketserver的基本使用方法实例分析
2020/04/09 Python
Python程序慢的重要原因
2020/09/04 Python
连卡佛中国官网:Lane Crawford中文站
2018/01/27 全球购物
Brora官网:英国领先的羊绒服装品牌
2019/08/28 全球购物
Currentbody美国/加拿大:美容仪专家
2020/03/09 全球购物
Chemist Warehouse中文网:澳洲连锁大药房
2021/02/05 全球购物
科室工作个人总结的自我评价
2013/10/29 职场文书
大学生关于奋斗的演讲稿
2014/01/09 职场文书
酒后驾驶检讨书
2014/01/27 职场文书
人民教师的自我评价分享
2014/02/21 职场文书
中学教师暑期培训方案
2014/08/27 职场文书
行政文员实习自我鉴定范文
2014/09/14 职场文书
使用react-virtualized实现图片动态高度长列表的问题
2021/05/28 Javascript
 Python 中 logging 模块使用详情
2022/03/03 Python