python调用百度查询关键字_Python模拟搜索百度关键字
經常使用百度搜索一些資料,故用Python模擬發送請求。
!/usr/bin/env python
# coding=utf8
#####################
name : bd.py
author: jaysonzhang
date : 2013-08-04
#####################
import urllib2
import string
import urllib
import re
import random
#設置多個user_agents,防止百度限制IP
user_agents = ['Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20130406 Firefox/23.0', \
'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:18.0) Gecko/20100101 Firefox/18.0', \
'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/533+ \
(KHTML, like Gecko) Element Browser 5.0', \
'IBM WebExplorer /v0.94', 'Galaxy/1.0 [en] (Mac OS X 10.5.6; U; en)', \
'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)', \
'Opera/9.80 (Windows NT 6.0) Presto/2.12.388 Version/12.14', \
'Mozilla/5.0 (iPad; CPU OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) \
Version/6.0 Mobile/10A5355d Safari/8536.25', \
'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) \
Chrome/28.0.1468.0 Safari/537.36', \
'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.0; Trident/5.0; TheWorld)']
#組裝url,搜索后返回結果
def baidu_search(keyword,pn):
p= {'wd': keyword}
#wd 代表關鍵字 pn 代表頁碼 cl=3 代表網頁搜索
access_url=("http://www.baidu.com/s?"+urllib.urlencode(p)+"&pn={0}&cl=3&rn=10").format(pn)
#res=urllib2.urlopen(("http://www.baidu.com/s?"+urllib.urlencode(p)+"&pn={0}&cl=3&rn=10").format(pn))
res=urllib2.urlopen(access_url)
html=res.read()
return html
#查找匹配關鍵字的所有結果,追加的結果以列表返回
def getList(regex,text):
arr = []
res = re.findall(regex, text)
if res:
for r in res:
arr.append(r)
return arr
#查找匹配關鍵字的所有結果
def getMatch(regex,text):
res = re.findall(regex, text)
if res:
return res[0]
return ""
#清除搜索結果中標題多余的html標簽
def clearTag(text):
p = re.compile(u'<[^>]+>')
retval = p.sub("",text)
return retval
#清除百度搜索后結果列表里存在的換行符和TAB符,以便下面正則表達式不用處理這些字符
def subContent(content):
content=re.sub('\n','',content)
content=re.sub('\t','',content)
return content
#開始搜索
def geturl(keyword,totalpage):
for page in range(totalpage):
print 'Now Page %d Result:' %(page+1)
pn=page*10+1
#開始搜索,從第一頁開始
html = baidu_search(keyword,pn)
content = unicode(html, 'utf-8','ignore')
#clean \n \t
content = subContent(content)
#得到左側搜索結果列表
arrList = getList(u"
.*?<\/a>", content)#遍歷左側搜索結果列表
for item in arrList:
regex = u"
(.*?)<\/a>"link = getMatch(regex,item)
#獲取百度返回帶加密串的url
url = link[0]
#獲取標題
title = clearTag(link[1]).encode('utf8')
#獲取搜索結果的URL真實地址
try:
domain=urllib2.Request(url)
r=random.randint(0,11)
domain.add_header('User-agent', user_agents[r])
domain.add_header('connection','keep-alive')
response=urllib2.urlopen(domain)
uri=response.geturl()
print "[%s]---->[%s]" %(title,uri)
except:
continue
if __name__=='__main__':
#輸入要顯示的總頁數
totalpage=int( raw_input('input totalpage :') )
#輸入關鍵字
key=u'%s' %( raw_input('input key word:') )
geturl(key,totalpage)
總結
以上是生活随笔為你收集整理的python调用百度查询关键字_Python模拟搜索百度关键字的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 基于51单片机+DS1302时钟模块+L
- 下一篇: lodash 常用的方法总结(持续更新)