前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python网络爬虫--简单爬取糗事百科

python网络爬虫--简单爬取糗事百科

作者头像
用户2038589
发布2018-09-06 15:29:59
4750
发布2018-09-06 15:29:59
举报
文章被收录于专栏:青青天空树

  刚开始学习python爬虫,写了一个简单python程序爬取糗事百科。

  具体步骤是这样的:首先查看糗事百科的url:http://www.qiushibaike.com/8hr/page/2/?s=4959489,可以发现page后的数据代表第几页。

  然后装配request,注意要设置user_agent

代码语言:javascript
复制
1 user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
2 headers = {'User-Agent': user_agent}
3 request=urllib2.Request(url,headers=headers)
4 response=urllib2.urlopen(request)

  然后获取返回的数据

代码语言:javascript
复制
content=response.read().decode('utf-8')

  然后是关键,使用正则匹配出所有的具体内容。这里可以使用浏览器的检查功能查看页面结构,写出相对应的正则式,比如我们对下面的<div class="content">...</div>进行匹配的正则式如下

代码语言:javascript
复制
pattern=re.compile('<div class="content">....<span>(.*?)</span>...</div>',re.S)

  (.*?)   :表示组,该部分为一个整体,将该部分匹配到字符串作为返回值返回,findall表示找到所有匹配的字符串,以序列的形式返回

  参数re.S表示"."点号匹配所有字符包括换行

下面是完整代码

代码语言:javascript
复制
 1 import urllib
 2 import urllib2
 3 import re
 4 import time
 5 
 6 page=2
 7 f=open("D:\qiushi.txt","r+")
 8 user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
 9 headers = {'User-Agent': user_agent}
10 while page<100:
11     url="http://www.qiushibaike.com/8hr/page/"+str(page)+"/?s=4959460"
12 
13     print url
14     try:
15         request=urllib2.Request(url,headers=headers)
16         response=urllib2.urlopen(request)
17         content=response.read().decode('utf-8')
18         # print content
19         pattern=re.compile('<div class="content">....<span>(.*?)</span>...</div>',re.S)
20         items=re.findall(pattern,content)
21         f.write((url+"\n").encode('utf-8'))
22         for item in items:
23             print "------"
24             item=item+"\n"
25             print item
26             f.write("------\n".encode('utf-8'))
27             f.write(item.replace('<br/>','\n').encode('utf-8'))
28     except urllib2.URLError,e:
29         if hasattr(e,"code"):
30             print e.code
31         if hasattr(e,"reason"):
32             print e.reason
33     finally:
34         page+=1
35         time.sleep(1)

这里我是将找到的输出到d盘下的qiushi.txt文件

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2017-02-23 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档