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

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

常用方法介绍

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)+" ")

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("

.*?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)+" ")

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值