#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import re
import urllib2
from BeautifulSoup import BeautifulSoup
def search(key):
#请求搜索链接,关键字用参数key代替
search_url='http://www.baidu.com/s?ie=UTF-8&wd=key'
req=urllib2.urlopen(search_url.replace('key',key))
#计数变量,用来记录页数
count = 1
#主循环,抓取每一页的url,直到最后一页
while 1:
print " 33[1;31mpage %s: 33[0m" % count
html=req.read()
soup=BeautifulSoup(html)
f = open("result.txt",'a')
#url在<span>...</span>中,
content = soup.findAll('span',attrs={'class':'g'})
#对每一个对象解析
for i in content:
pat = re.compile("^(.+?) .*$")
#i为对象,所以用i.text转换为字符串
url = re.search(pat,i.text)
#url有可能匹配不到
if url:
f.write(url.group(1)+"n")
print url.group(1)
else:
next
f.close()
#得到“下一页”的链接。除了第一页和最后一页,其他的会有2个元素。第一个为上一页,第二个为下一页。
#这里取倒数第一个元素
next_page='http://www.baidu.com'+soup('a',{'href':True,'class':'n'})[-1]['href']
#最后一页只有一个元素,倒数第一个是“上一页”,所以判断一下,如果只有一个元素,并且不是第一页就结束。
#否则可能会造成死循环
if count >1 and len(soup('a',{'href':True,'class':'n'}))==1:
print " 33[1;31mcomplete! 33[0m"
break
#不是最后一页就继续
else:
req=urllib2.urlopen(next_page)
count += 1
if __name__=='__main__':
key = "hello world!"
search(key)
原文:http://blog.csdn.net/adidala/article/details/42842489
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!