Python爬虫爬取内涵吧段子案例系列之八
2017-07-20 19:11
267 查看
不多说,直接上代码
# 爬取内涵吧段子的案例 import re import requests class Duanzi(object): def __init__(self): self.baseURL = 'http://www.neihan8.com/article/index' self.headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko'} # 表示页码,默认为第一页 self.page = 1 # 用来匹配每一页的每条段子, re.S 表示启用DOTALL模式( .也可以匹配换行符) # .* 贪心算法(尽可能多匹配 .) # .*? 非贪心算法(尽可能少匹配 .) self.pattern_page = re.compile(r'<div class="desc">(.*?)</div>', re.S) # self.pattern_page = re.compile(r'<div class="f18 mb20">(.*?)</div>', re.S) # &(.*?); 表示匹配 HTML实体字符 如: # <(.*?)> 表示匹配所有的标签 如:<p> <\br> # \s 匹配空白字符、换行符,但是不包括全角空格 # " " 表示匹配全角空格 self.pattern_content = re.compile(r'&(.*?);|<(.*?)>|\s| >') def loadpage(self): '''抓取每一页所有的段子''' print("正在抓取第%s页段子" % self.page) if self.page==1: # 处理每一页的url地址 url = self.baseURL +'.html' else: # 处理每一页的url地址 url = self.baseURL + '_'+str(self.page) + '.html' # 网页默认编码为gbk,发送请求,返回相应数据 html_gbk = requests.get(url, headers=self.headers).content # 将gbk编码的网页转化为utf8 # html = html_gbk.decode('gbk').encode('utf-8') html = html_gbk.decode('utf8') # 匹配文本,获取所有段子的列表 content_list = self.pattern_page.findall(html) self.write_page(content_list) def write_page(self, content_list): '''把每一页的段子内容写入到磁盘文件中''' print("正在写入第%s页的段子内容" % self.page) # 切记这里的a是追加模式 with open('duanzi.txt', 'a') as f: for content in content_list: # 匹配内容,去除无用的字符 content2 = self.pattern_content.sub("", content) f.write(content2) f.write('\n\n') def duanzi_spider(self): while True: command = input("亲!请按回车键继续爬虫(按q键退出...):") if command == 'q': break self.loadpage() self.page += 1 if __name__ == '__main__': duanzi = Duanzi() duanzi.duanzi_spider()
相关文章推荐
- Python爬虫——7-1.scrapy框架案例-爬取内涵段子
- Python爬虫系列之一:爬取糗事百科段子(24小时)
- 使用python 编写 抓取内涵段子动态图的简单爬虫
- Python爬虫模拟真实登录案例系列之十二
- Python爬虫:抓取内涵段子1000张搞笑图片-下篇(小爬虫优化篇)
- python编写简单的网络爬虫——爬取内涵段子(请求头header反爬,适用瀑布流试网站,淘宝、知乎等)
- Python爬虫Xpath和lxml类库系列之九
- Python爬虫系列之二:爬取2018公务员招考职位信息
- Python爬虫小案例:豆瓣电影TOP250
- pyhton爬虫--正则爬取内涵段子文字
- Python爬虫入门案例:获取百词斩已学单词列表
- python爬虫-糗事百科段子内容
- Python爬虫学习系列教程
- Python爬虫入门案例
- [Python爬虫] scrapy爬虫系列 <一>.安装及入门介绍
- Python爬虫系列博客
- Python爬虫系列(六):搜索文档树
- python爬虫案例——新浪腾讯股票数据采集
- python爬虫系列之爬取百度文库(三)