python正则表达式简单爬虫入门+案例(爬取猫眼电影TOP榜)
2017-09-05 15:06
946 查看
用正则表达式实现一个简单的小爬虫
常用方法介绍
1、导入工具包
import requests #导入请求模块 from flask import json #导入json模块 from requests.exceptions import RequestException #异常捕捉模块 import re #导入正则模块 from multiprocessing import Pool #导入进程模块
2、获取页面
response =requests.get(url) url:当前需要爬取的链接 requests.get()获得页面
3、if response.status_code ==200:
#验证状态码 response.status_code:获取状态码 200:表示正常,连接成功
4、response.text:得到页面内容
例如:response =requests.get(url)
5、except RequestException:捕捉异常
try: ... except RequestException: ...
6、pat = re.compile():编译正则表达式
#简单的正则基础
7、items =re.findall(pat,html)
pat:编译过的正则表达式 html:用response.text得到的页面内容 re.findall():找到所有匹配的内容
8、打开文件
with open('result','a',encoding='utf-8')as f with as :打开自动闭合的文件并设立对象f进行操作 result:文件名字 a:打开方式是续写模式 encoding:编码格式
9、写入文件
f.write(json.dumps(conrent,ensure_ascii =False)+'\n') json.dumps:以json方式写入
10、简单进程
pool = Pool() #创建进程池 pool.map(func,[i*10 for i in range(10)]) [i*10 for i in range(10)]:生成器,生成0到9的数字乘以10的结果,生成一个列表为[0,10,20....] func:函数 map:将函数作用于列表每一个元素
11、yield:生成器
案例:用上面的工具完成爬去猫眼电影TOP榜
#__author:PL.Li #导入需要使用的模块 import requests from flask import json from requests.exceptions import RequestException import re from multiprocessing import Pool #尝试连接获取页面 def get_response(url): try: response =requests.get(url) if response.status_code ==200: return response.text return None except RequestException: return None #正则匹配需要的内容 def re_one_page(html): #超级长的正则表达式进行匹配,匹配到的是个集合。 pat =re.compile('<dd>.*?board-index.*?">(/d+?)</i>.*?data-src="(.*?).*?name"><a.*?">(.*?)"class=.*?class="star">' '(.*?)</p>.*?releasetime">(.*?)</p>.*?integer">(.*?)</i>.*?fraction">(.*?)</i>.*?</dd>',re.S) #用迭代进行异步操作 items =re.findall(pat,html) for item in items: yield { 'index':item[0], 'image':item[1], 'title':item[2], 'actor':item[3].strip()[3:], 'time':item[4].strip(), 'score':item[5]+item[6] } #保存写入文件 def write_file(conrent): with open('result','a',encoding='utf-8')as f: f.write(json.dumps(conrent,ensure_ascii =False)+'\n') f.close() #配置启动函数 def main(offset): url ='http://maoyan.com/board'+str(offset) html=get_response(url) for item in re_one_page(html): write_file(item) #使用多进程加速一秒完成 if __name__ == '__main__': pool = Pool() pool.map(main,[i*10 for i in range(10)])
相关文章推荐
- python3爬虫之入门和正则表达式,获取IP地址, 隐马尔可夫模型及其在分词中的简单应用
- python3爬虫之入门基础和正则表达式
- python爬虫入门(1) 基础知识 ; 正则表达式 Re 模块
- Python爬虫入门七之正则表达式
- python用字符串操作20行代码简单爬虫入门+案例(爬取一章《三体》小说)
- Python爬虫入门七之正则表达式
- [Python3]爬虫入门之正则表达式
- Python爬虫入门七之正则表达式
- [转载]Python爬虫入门七之正则表达式
- Python入门-编写抓取网站图片的爬虫-正则表达式
- python 爬虫入门之正则表达式 一
- python3爬虫之入门和正则表达式
- python3 爬虫入门(三)正则表达式基本使用
- python3爬虫入门之正则表达式
- python3爬虫之入门和正则表达式
- Python爬虫入门七之正则表达式
- Python爬虫入门(7):正则表达式
- python3爬虫之入门和正则表达式
- python3爬虫之入门和正则表达式
- python的小实验代码的备份,主要偏向于爬虫方向,难点是正则表达式和编码转换[入门]