1.使用三个库:urllib2, re , lxml ,自行百度安装,
# -*- coding:utf-8 -*-
import urllib2
import re
import lxml.html as html
def get_url(url): #封装一次url的请求,获得3个参数
User_Agent = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.90 Safari/537.36'
header = {
'User-Agent':User_Agent
} #不使用headers传参数將无法获取到页面数据
try:
req = urllib2.Request(url,headers=header)
response = urllib2.urlopen(req)
content = response.read().decode('utf-8')
# print content
tree = html.fromstring(content) #将源码进行转化,这样就可以通过tree来使用xpath,
aa = tree.xpath('//*[@id="content-left"]//div[@class="article block untagged mb15"]')
wenben = tree.xpath('//text()')
wenben = "".join(wenben).strip() #获取当前页面中文本,
meiyetiaoshu = len(aa) #获取当前页面中有几条数据
return tree, meiyetiaoshu, wenben,
except urllib2.URLError, e:
if hasattr(e, 'code'):
print e.code
if hasattr(e, 'reason'):
print e.reason
#抓取每一页中的所有条数数据
def page_one(tree,wenben,meiyetiaoshu):
for i in range(1,meiyetiaoshu+1):
zuozhe = tree.xpath('//*[@id="content-left"]//div[{}]/div[1]/a[2]/@title'.format(i))
if not zuozhe: #对匿名用户的处理,
zuozhe = tree.xpath('//*[@id="content-left"]//div[{}]/div[1]/span[2]/h2/text()'.format(i))
print i,zuozhe[0] #获取得到用户名称,
duanzi = tree.xpath('//*[@id="content-left"]//div[{}]/a/div/span/text()'.format(i))
print duanzi[0].strip() #获取得到用户说的笑话信息,
sub_zuozhe= re.sub(u'(\*|\(|\)|\~|\^)','',zuozhe[0]) #里面有特殊字符,将其中的特殊字符替换掉
wenben = re.sub(u'(\*|\(|\)|\~|\^)','',wenben) #将文本中的特殊字符页替换掉,
haoxiao_group = re.search(u'%s[\d\D]+?(\d+ 好笑)'%sub_zuozhe,wenben)
print haoxiao_group.group(1).strip() 获取得到里面有多少人觉得好笑,评论数也可以用相同的方法抓取
#抓取前10页数据,
for page in range(1,11):
url = 'http://www.qiushibaike.com/hot/page/%s/'%str(page) #前10页的url
tree, meiyetiaoshu, wenben = get_url(url)
page_one(tree=tree,wenben=wenben,meiyetiaoshu=meiyetiaoshu)