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根据文件大小打log日志
Oct 09 Python
Python中的高级数据结构详解
Mar 27 Python
将Django使用的数据库从MySQL迁移到PostgreSQL的教程
Apr 11 Python
ubuntu16.04制作vim和python3的开发环境
Sep 23 Python
Python语言快速上手学习方法
Dec 14 Python
python实现月食效果实例代码
Jun 18 Python
使用python socket分发大文件的实现方法
Jul 08 Python
Python解析json时提示“string indices must be integers”问题解决方法
Jul 31 Python
Python之——生成动态路由轨迹图的实例
Nov 22 Python
JetBrains PyCharm(Community版本)的下载、安装和初步使用图文教程详解
Mar 19 Python
python实现俄罗斯方块小游戏
Apr 24 Python
pycharm设置默认的UTF-8编码模式的方法详解
Jun 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
Phpbean路由转发的php代码
2008/01/10 PHP
常用的php对象类型判断
2008/08/27 PHP
php UBB 解析实现代码
2011/11/27 PHP
浅谈Laravel队列实现原理解决问题记录
2017/08/19 PHP
PHP实现chrome表单请求数据转换为接口使用的json数据
2021/03/04 PHP
List the UTC Time on a Computer
2007/06/11 Javascript
设为首页和收藏的Javascript代码(亲测兼容IE,Firefox,chrome等浏览器)
2013/11/18 Javascript
JS动态创建DOM元素的方法
2015/06/09 Javascript
微信开发 消息推送实现代码
2016/10/21 Javascript
jquery css实现邮箱自动补全
2016/11/14 Javascript
JS键盘版计算器的制作方法
2016/12/03 Javascript
微信小程序 用户数据解密详细介绍
2017/01/09 Javascript
js轮播图透明度切换(带上下页和底部圆点切换)
2017/04/27 Javascript
深入学习nodejs中的async模块的使用方法
2017/07/12 NodeJs
Vue.js 单页面多路由区域操作的实例详解
2017/07/17 Javascript
vue+node实现图片上传及预览的示例方法
2018/11/22 Javascript
js使用swiper实现层叠轮播效果实例代码
2018/12/12 Javascript
JS匿名函数内部this指向问题详析
2019/05/10 Javascript
Python信息抽取之乱码解决办法
2017/06/29 Python
Python日志无延迟实时写入的示例
2019/07/11 Python
postman模拟访问具有Session的post请求方法
2019/07/15 Python
python类中super() 的使用解析
2019/12/19 Python
Python参数传递实现过程及原理详解
2020/05/14 Python
详解python程序中的多任务
2020/09/16 Python
劳资专员岗位职责
2013/12/27 职场文书
《山谷中的谜底》教学反思
2014/04/26 职场文书
会议欢迎标语
2014/06/30 职场文书
海洋科学专业求职信
2014/08/10 职场文书
2014年幼儿园教学工作总结
2014/12/04 职场文书
出纳工作检讨书范文
2014/12/27 职场文书
学校教学工作总结2015
2015/05/19 职场文书
2016暑期师德培训心得体会
2016/01/09 职场文书
《自己去吧》教学反思
2016/02/16 职场文书
《去年的树》教学反思
2016/02/18 职场文书
解析高可用Redis服务架构分析与搭建方案
2021/06/20 Redis
win10如何快速切换窗口 win10切换窗口快捷键分享
2022/07/23 数码科技