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 相关文章推荐
写了个监控nginx进程的Python脚本
May 10 Python
pyside写ui界面入门示例
Jan 22 Python
python中django框架通过正则搜索页面上email地址的方法
Mar 21 Python
Python中的字符串替换操作示例
Jun 27 Python
python Selenium爬取内容并存储至MySQL数据库的实现代码
Mar 16 Python
K-means聚类算法介绍与利用python实现的代码示例
Nov 13 Python
Python:Scrapy框架中Item Pipeline组件使用详解
Dec 27 Python
Python 实现遥感影像波段组合的示例代码
Aug 04 Python
如何修复使用 Python ORM 工具 SQLAlchemy 时的常见陷阱
Nov 19 Python
Python实现屏幕录制功能的代码
Mar 02 Python
通过python 执行 nohup 不生效的解决
Apr 16 Python
Python如何在bool函数中取值
Sep 21 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动态生成JavaScript代码
2009/03/09 PHP
php反弹shell实现代码
2009/04/22 PHP
PHP 程序员应该使用的10个组件
2009/10/31 PHP
discuz authcode 经典php加密解密函数解析
2020/07/12 PHP
PHP类的静态(static)方法和静态(static)变量使用介绍
2012/02/19 PHP
php中隐形字符65279(utf-8的BOM头)问题
2014/08/16 PHP
PHP连接MYSQL数据库实例代码
2016/01/20 PHP
PHP 实现公历日期与农历日期的互转换
2017/09/13 PHP
HR vs ForZe BO3 第一场 2.13
2021/03/10 DOTA
jquery异步调用页面后台方法&amp;#8207;(asp.net)
2011/03/01 Javascript
jQuery实现长文字部分显示代码
2013/05/13 Javascript
jQuery插件EasyUI校验规则 validatebox验证框
2015/11/29 Javascript
jQuery实现边框动态效果的实例代码
2016/09/23 Javascript
js获取ip和地区
2017/03/10 Javascript
JS简单实现点击跳转登陆邮箱功能的方法
2017/10/31 Javascript
vue-cli构建项目下使用微信分享功能
2018/05/28 Javascript
Vue CLI 3搭建vue+vuex最全分析(推荐)
2018/09/27 Javascript
vue2中引用及使用 better-scroll的方法详解
2018/11/15 Javascript
axios异步提交表单数据的几种方法
2019/08/11 Javascript
vue模块移动组件的实现示例
2020/05/20 Javascript
Python多线程编程(八):使用Event实现线程间通信
2015/04/05 Python
Python3.7中安装openCV库的方法
2018/07/11 Python
python dumps和loads区别详解
2020/02/04 Python
Python将字典转换为XML的方法
2020/08/01 Python
css3绘制天猫logo实现代码
2012/11/06 HTML / CSS
巴西服装和鞋子购物网站:Marisa
2018/10/25 全球购物
JENNIFER BEHR官网:各种耳环和发饰
2020/06/07 全球购物
Set里的元素是不能重复的,那么用什么方法来区分重复与否呢? 是用==还是equals()? 它们有何区别?用contains来区分是否有重复的对象。还是都不用
2013/07/30 面试题
食品安全演讲稿
2014/09/01 职场文书
党的群众路线教育实践活动个人整改措施
2014/10/27 职场文书
遗愿清单观后感
2015/06/09 职场文书
优秀学生干部主要事迹材料
2015/11/04 职场文书
《小摄影师》教学反思
2016/02/18 职场文书
python基于tkinter制作无损音乐下载工具
2021/03/29 Python
jQuery ajax - getScript() 方法和getJSON方法
2021/05/14 jQuery
如何使用Tkinter进行窗口的管理与设置
2021/06/30 Python