博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python正则表达式简单爬虫入门+案例(爬取猫眼电影TOP榜)
阅读量:7234 次
发布时间:2019-06-29

本文共 2357 字,大约阅读时间需要 7 分钟。

用正则表达式实现一个简单的小爬虫

常用方法介绍

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 fwith 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 requestsfrom flask import jsonfrom requests.exceptions import RequestExceptionimport refrom 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('
.*?board-index.*?">(/d+?).*?data-src="(.*?).*?name">
(.*?)"class=.*?class="star">' '(.*?)

.*?releasetime">(.*?)

.*?integer">(.*?).*?fraction">(.*?).*?
',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)])

转载地址:http://bllfm.baihongyu.com/

你可能感兴趣的文章
中国500强的CEO们对80.90后的忠告
查看>>
mysql使用
查看>>
软考中高项学员:2016年3月28日作业
查看>>
Android 调试桥abd
查看>>
MTU-1
查看>>
2018.3.22 13周4次课
查看>>
2018.4.9 15周4次课
查看>>
我的友情链接
查看>>
手机上网的秘密1
查看>>
编写一个Linux虚拟网卡来实现类NVI
查看>>
织梦图集的使用
查看>>
跳出率与退出率的详细解析
查看>>
linux之路开始啦
查看>>
我的友情链接
查看>>
阿里云 OSS
查看>>
把字符串分隔成多行的多种方法实践
查看>>
yum详解
查看>>
对于在window7-64位环境下安装软件的问题
查看>>
hdu5831 Rikka with Parenthesis II
查看>>
如何做好业务系统运行仿真
查看>>