最简单的爬取网页找有用信息,难点应该是正则锁定有用信息部分,看了一些其他大神的正则,最后还是决定按照自己理解写一个,果然我头脑相对简单,写出来的粗糙而易理解,也完成了自己想要的需求,就这样了~
# -*- coding:utf-8 -*-
import urllib
import urllib2
import re
page=1
url='http://www.qiushibaike.com/hot/page/'+str(page)
user_agent='Mozilla/4.0 (compatiable; MSIE 5.5; Windows NT)'
headers={'User-Agent':user_agent}
try:
request=urllib2.Request(url,headers=headers)
response=urllib2.urlopen(request)
content= response.read().decode('utf-8')
pattern=re.compile('<span>(.*?)</span>',re.S)
items=re.findall(pattern,content)
for item in items:
print item
except urllib2.URLError as e:
if hasattr(e,"code"):
print e.code
if hasattr(e,"reason"):
print e.reason