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 MySQLdb Linux下安装笔记
May 09 Python
Python中的lstrip()方法使用简介
May 19 Python
Python机器学习算法之k均值聚类(k-means)
Feb 23 Python
Python函数参数操作详解
Aug 03 Python
详解python Todo清单实战
Nov 01 Python
python3+selenium实现126邮箱登陆并发送邮件功能
Jan 23 Python
对Python3 pyc 文件的使用详解
Feb 16 Python
python dataframe NaN处理方式
Dec 26 Python
tensorflow实现二维平面模拟三维数据教程
Feb 11 Python
在PyCharm中实现添加快捷模块
Feb 12 Python
scrapy爬虫:scrapy.FormRequest中formdata参数详解
Apr 30 Python
详解python的变量缓存机制
Jan 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支持页面回退的两种方法[转]
2007/02/14 PHP
PHP 计算代码执行耗时的代码修正网上普遍错误
2011/05/14 PHP
PHP简单的MVC框架实现方法
2015/12/01 PHP
基于PHP技术开发客服工单系统
2016/01/06 PHP
一个实用的php验证码类
2017/07/06 PHP
关于javascript document.createDocumentFragment()
2009/04/04 Javascript
javascript 验证日期的函数
2010/03/18 Javascript
javascrpt绑定事件之匿名函数无法解除绑定问题
2012/12/06 Javascript
做好七件事帮你提升jQuery的性能
2014/02/06 Javascript
javascript:void(0)的问题使用探讨
2014/04/10 Javascript
AngularJS基础 ng-include 指令示例讲解
2016/08/01 Javascript
解析预加载显示图片艺术
2016/12/05 Javascript
详解基于webpack搭建react运行环境
2017/06/01 Javascript
原生JS实现移动端web轮播图详解(结合Tween算法造轮子)
2017/09/10 Javascript
layui点击按钮添加可编辑的一行方法
2018/08/15 Javascript
Vue源码解析之数组变异的实现
2018/12/04 Javascript
Bootstrap 实现表格样式、表单布局的实例代码
2018/12/09 Javascript
详解vue微信网页授权最终解决方案
2019/06/16 Javascript
vue页面切换项目实现转场动画的方法
2019/11/12 Javascript
编写Python CGI脚本的教程
2015/06/29 Python
Python numpy生成矩阵、串联矩阵代码分享
2017/12/04 Python
Windows下Anaconda2安装NLTK教程
2018/09/19 Python
python实现共轭梯度法
2019/07/03 Python
Python打开文件、文件读写操作、with方式、文件常用函数实例分析
2020/01/07 Python
使用TensorFlow直接获取处理MNIST数据方式
2020/02/10 Python
keras训练曲线,混淆矩阵,CNN层输出可视化实例
2020/06/15 Python
详细分析Python垃圾回收机制
2020/07/01 Python
序列化Python对象的方法
2020/08/01 Python
CSS3截取字符串实例代码【推荐】
2018/06/07 HTML / CSS
当当网软件测试笔试题
2015/11/24 面试题
卫校护理专业毕业生求职信
2013/11/26 职场文书
8和9的加减法教学反思
2014/05/01 职场文书
新闻稿怎么写
2015/07/18 职场文书
青年岗位能手事迹材料(2016推荐版)
2016/03/01 职场文书
Python机器学习之底层实现KNN
2021/06/20 Python
Go语言安装并操作redis的go-redis库
2022/04/14 Golang