# -*- 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 (compatible; 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('<div class="author clearfix">.*?<h2>(.*?)</h2>.*?"content">.*?<span>(.*?)</span>.*?</div>(.*?)<div class="stats.*?class="number">(.*?)</.*?number">(.*?)</i>', re.S)
imgPattern = re.compile('<img src="(.*?)"', re.S)
items = re.findall(pattern, content)
# 分别对应的是 昵称,内容,图片,好笑数,评论数
for item in items:
haveImg = re.search("img",item[2])
replaceBR = re.compile('<br/>')
content = re.sub(replaceBR,"\n",item[1])
if not haveImg:
print item[0], content, item[3], item[4]
else:
imgUrl = re.findall(imgPattern, item[2])[0]
print item[0], content, imgUrl, item[3], item[4]
except urllib2.URLError, e:
if hasattr(e, "code"):
print e.code
if hasattr(e, "reason"):
print e.reason
网友评论