python正则表达式简单爬虫入门+案例(爬取猫眼电影TOP榜)

来源:互联网 发布:网络招生方案 编辑:程序博客网 时间:2024/05/18 02:25

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

这里写图片描述

常用方法介绍

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)]:生成器,生成09的数字乘以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('<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)])
阅读全文
0 0
原创粉丝点击