python 爬虫(正则表达式案例)
2018-02-01 15:20
555 查看
一直对爬虫充满着好奇,最近终于有时间来好好学习一番,我是在网上找到传智播客的课程视频,跟着视频学习python编写爬虫的,很多案例都很通用,特别记录一下,以后工作中遇到了可以直接拿来使用。
下面这个案例是使用正则表达式来提取内涵段子网上的段子。该示例是在python3的环境下运行的
下面这个案例是使用正则表达式来提取内涵段子网上的段子。该示例是在python3的环境下运行的
import urllib.request import re import random class Spider: def headers(self): """ 随机产生User-Agent的header :return: """ headers_list = [ "User-Agent:Mozilla/5.0(compatible;MSIE9.0;WindowsNT6.1;Trident/5.0", "User-Agent:Mozilla/4.0(compatible;MSIE8.0;WindowsNT6.0;Trident/4.0)", "User-Agent:Mozilla/4.0(compatible;MSIE7.0;WindowsNT6.0)", "Mozilla/5.0(WindowsNT6.1;rv:2.0.1)Gecko/20100101Firefox/4.0.1", "Opera/9.80(WindowsNT6.1;U;en)Presto/2.8.131Version/11.11", "Mozilla/4.0(compatible;MSIE7.0;WindowsNT5.1;TencentTraveler4.0)", "Mozilla/4.0(compatible;MSIE7.0;WindowsNT5.1;Maxthon2.0)", "Mozilla/4.0(compatible;MSIE7.0;WindowsNT5.1;360SE)", "Mozilla/4.0(compatible;MSIE7.0;WindowsNT5.1)", ] ua_agent = random.choice(headers_list) return ua_agent def load_page(self, url, ua_agent): """ 加载一个页面的数据 :param url: 页面的url :param ua_agent: User-Agent :return: 返回页面的html数据 """ headers = {"User-Agent": ua_agent} request = urllib.request.Request(url, headers=headers) response = urllib.request.urlopen(request) return response.read() def parse(self, html): """ 解析页面的数据 :param html: :return: """ # re.S 是将所有的字符串作为一个整体进行匹配; re.I 表示忽略大小写 patten = re.compile('<h1 class="title">.*?</h1>', re.S) result = patten.findall(html.decode("utf-8")) return result def write(self, content): """ 保存数据,把提取出的数据写入文件中 :param content: 提取的数据 :return: """ # 返回的content是一个list,写入文件的时候遍历list逐条写入 for each in content: # 把页面中的多余字符用空格替代 each = each.replace('<h1 class="title">', '').replace('<p>', '').replace('</p>', '').replace('</h1>', '') # print(each) with open("duanzi.text", "w") as f: f.write(each + "\n") def main(self, url): """ :param url: 爬取数据的起始页面url :return: """ html = self.load_page(url) content = self.parse(html) self.write(content) if __name__ == "__main__": url = "http://www.neihanshequ.com" spider = Spider() spider.main(url)
相关文章推荐
- [python自学笔记]正则表达式和爬虫案例
- Python笔记2--正则表达式与爬虫案例
- Python爬虫(十一)_案例:使用正则表达式的爬虫
- python正则表达式简单爬虫入门+案例(爬取猫眼电影TOP榜)
- python使用正则表达式编写网页小爬虫
- Python爬虫入门七之正则表达式
- 运维学python之爬虫基础篇(五)正则表达式
- Python爬虫知识(2)——正则表达式复习
- 04 Python正则表达式 爬虫程序 变量的引用,浅拷贝,深拷贝 多线程 进程锁 数据库模块
- Python爬虫正则表达式和re模块系列之七
- python 爬虫入门之正则表达式 一
- python正则表达式基础以及案例
- 【Python3 爬虫】08_正则表达式(元字符与语法)
- 【python爬虫专题】解析方法 <3> 正则表达式学习
- Python 爬虫学习笔记之正则表达式
- python——爬虫学习——正则表达式与Re库-(4)
- python 爬虫003-正则表达式简单介绍
- Python爬虫入门七之正则表达式
- python爬虫之正则表达式
- 第01阶段-基础入门-02-Python 爬虫基础-21节=====12.认识正则表达式