爬糗事百科的段子(爬多页)
来源:互联网 发布:三星5830root软件 编辑:程序博客网 时间:2024/05/21 08:02
爬糗事百科
网址:http://www.qiushibaike.com/hot/
首先设置headers:
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' headers = { 'User-Agent' : user_agent }用headers获取网页源代码:
request=urllib2.Request(url,headers = headers) response=urllib2.urlopen(request) content =response.read().decode('utf-8')编写正则获取想要的内容:
pattern = re.compile('.*?<h2>\n(.*?)\n</h2>.*?<span>\n\n\n(.*?)\n</span>.*?<i class="number">(.*?)</i>(.*?).*?number">(.*?)</i>(.*?)</a>',re.S) items=re.findall(pattern,content)如何实现翻页?
http有两种请求方式 get和post
每一页的网址都不同
第一页:https://www.qiushibaike.com/hot/
第二页:https://www.qiushibaike.com/hot/page/2
第三页:https://www.qiushibaike.com/hot/page/3
。。。
所以想要爬多页加一个for循环即可:
for page in range(1,5): url = 'http://www.qiushibaike.com/hot/page/' + str(page)整体代码:
__author__ = 'kkk'#--*--coding:utf-8--*--import urllib2import refor page in range(1,5): 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('.*?<h2>\n(.*?)\n</h2>.*?<span>\n\n\n(.*?)\n</span>.*?<i class="number">(.*?)</i>(.*?).*?number">(.*?)</i>(.*?)</a>',re.S) items=re.findall(pattern,content) for item in items: haveImg = re.search("img",item[3]) if not haveImg: s=re.sub('<br/>','',item[1]) print item[0],s,item[2],item[4] list=(item[0]+' '+s+item[2]+' '+item[4]) f1 = open('01.txt','a') f1.write(list.encode('utf-8')) f1.close() except urllib2.URLError,e: if hasattr(e,"code"): print e.code if hasattr(e,"reason"): print e.reason
阅读全文
0 0
- 爬糗事百科的段子(爬多页)
- 爬取糗事百科的段子Demo
- 爬取糗事百科段子
- 糗事百科段子爬取
- 用python 爬糗事百科的段子-1
- 用正则爬取糗事百科的段子
- 一个爬取糗事百科段子的简单爬虫
- 爬取糗事百科上的段子(BeautifulSoup)
- python爬虫爬取糗事百科的段子
- Python爬虫实战(1):爬取糗事百科段子
- Python爬虫实战(1):爬取糗事百科段子
- 一个简单的爬虫代码爬取糗事百科段子(selenium+ChromeDriver)
- python抓取糗事百科的段子
- Python实现抓取糗事百科的段子
- 【网络爬虫】爬取糗事百科段子
- 利用Scrapy爬取糗事百科段子
- python 爬虫 爬取糗事百科段子
- [Scrapy]爬取糗事百科段子
- 牛客网程序设计赛低年级组之数圈圈
- 封装OkHttpUtil
- kuangbin专题五 并查集 POJ3038 How Many Answers Are Wrong
- Long Dominoes (状态dp)
- 12月1号
- 爬糗事百科的段子(爬多页)
- 【多线程】-线程范围内共享数据的两种方式
- c#多线程_1
- 用树莓派搭建svn服务器
- 基于单片机的LED流水灯(着力解决加速减速bug问题)
- 添加表单姓名邮箱
- [INS-06006] Passwordless SSH connectivity not set up between the following node(s):
- 京东商城的分类
- 快速排序 C语言描述