python爬取糗事百科段子

初步爬取糗事百科第一页段子(发布人,发布内容,好笑数和评论数)

 1 #-*-coding:utf-8-*-
 2 import urllib
 3 import urllib2
 4 import re
 5 page = 1
 6 url ='http://www.qiushibaike.com/hot/page/'+str(page)
#第一页URL
7 headers={'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0'}
#浏览器的headers ,模拟浏览器去访问
8 request=urllib2.Request(url,headers=headers)
#构建请求request
9 response = urllib2.urlopen(request)
#通过urlopen获取页面代码
10 html=response.read()
#将获取的代码存入html变量 中
11 #print(html)
# 到这里就把这一页的URL爬取下来了
12 pattern=re.compile('<div class="author clearfix">.*?title.*?<h2>(.*?)</h2>.*?<div class="content">(.*?)</div>.*?<div class="stats">.*?number">(.*?)</i>.*?<span class="dash">.*?number">(.*?)</i>',re.S)
#挖出自己想要的内容
13 items=re.findall(pattern,html) 14 for item in items: 15 print(item[0])#发布人 16 print(item[1])#发布内容 17 print(item[2])#好笑数 18 print(item[3])#点赞数

对上面正则表达式略作解释:

(1).*? 是固定搭配

(2)(.*?)代表一个分组,能将每一个括号里匹配的内容输出到终端。如第一个item[0]代表第一个分组即发布人。

(3)re.S代表在匹配时为点任意匹配模式

爬取部分结果如下:

正则表达式过于繁琐,对其进行简化

1 pattern=re.compile('<div.*?"author.*?">.*?title.*?<h2>(.*?)</h2>.*?"content">(.*?)<!--.*?-->.*?"stats">.*?number">(.*?)</i>.*?"dash">.*?number">(.*?)</i>',re.S)

 

posted @ 2016-01-02 15:08  邬家栋  阅读(449)  评论(0编辑  收藏  举报