Python实现百度搜索内容抓取代码示例
本文介绍利用Python编写爬虫程序以提取百度搜索结果的完整代码实例。通过配置User-Agent池防止IP限制,使用urllib2库发起请求并解析HTML返回链接与标题。该示例展示了基础的网页抓取流程,适用于学习Python网络编程及数据提取技术,供开发者参考实现。
Python百度搜索爬虫概述
本文详细展示了如何使用Python编写爬虫程序来抓取百度搜索页面的内容。文中提供了具体的代码示例,旨在为读者的学习或实际工作提供有价值的参考,建议感兴趣的用户仔细阅读并尝试运行。
抓取原理与流程
搜索引擎在日常使用中极为普遍,现在可以通过Python爬虫技术提取百度搜索的内容。在此基础上,进一步对提取出的内容进行数据分析,可以简化搜索流程。以下是具体的实现案例。
代码实现示例
具体实现代码如下所示。
完整Python代码
# coding=utf8
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)']
def baidu_search(keyword,pn):
p= {'wd': keyword}
res=urllib2.urlopen(("http://www.baidu.com/s?"+urllib.urlencode(p)+"&pn={0}&cl=3&rn=100").format(pn))
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 ""
def clearTag(text):
p = re.compile(u'<[^>]+>')
retval = p.sub("",text)
return retval
def geturl(keyword):
for page in range(10):
pn=page*100+1
html = baidu_search(keyword,pn)
content = unicode(html, 'utf-8','ignore')
arrList = getList(u"<table.*?class="result".*?>.*?</a>", content)
for item in arrList:
regex = u"<h3.*?class="t".*?><a.*?href="(.*?)" rel="external nofollow" rel="external nofollow" .*?>(.*?)</a>"
link = getMatch(regex,item)
url = link[0]
#获取标题
#title = clearTag(link[1]).encode('utf8')
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 uri
except:
continue
if __name__=='__main__':
geturl('python')</a.*?href="(.*?)" rel="external nofollow" rel="external nofollow" .*?></h3.*?class="t".*?></table.*?class="result".*?>
总结与支持
以上就是本文介绍的全部内容,希望这些内容能对读者有所帮助,同时也欢迎大家继续支持本站获取更多技术资源。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









