使用 进程池Pool 提高爬取数据的速度。

 1 # !/usr/bin/python
2 # -*- coding:utf-8 -*-
3 import requests
4 from requests.exceptions import RequestException
5 import re
6 import json
7 from multiprocessing import Pool,Lock
8
9
10 # 获取单页数据信息;
11 def get_one_page(url, headers):
12 try:
13 response = requests.get(url, headers=headers)
14 if response.status_code == 200:
15 return response.text
16 return None
17 except RequestException:
18 return None
19
20 # 使用正则表达式解析数据;
21 def parse_one_page(html):
22 pattern = re.compile('<dd>.*?board-index.*?>(\d+)</i>.*?data-src="(.*?)".*?name"><a.*?>'
23 +'(.*?)</a>.*?star">(.*?)</p>.*?releasetime">(.*?)</p>.*?integer">'
24 +'(.*?)</i>.*?fraction">(.*?)</i>.*?</dd>', re.S)
25 items = re.findall(pattern, html)
26 # 将获取的数据以字典形式返回;
27 for item in items:
28 yield {
29 'index': item[0],
30 'image': item[1],
31 'title': item[2],
32 'actor': item[3].strip()[3:],
33 'time': item[4].strip()[5:],
34 'score': item[5]+item[6]
35 }
36
37 # 将字典转换为字符串保存,
38 def write_to_file(content):
39 lock.acquire()
40 with open('result.txt', 'a', encoding="utf-8") as f:
41 f.write(json.dumps(content, ensure_ascii=False) + "\n")
42 f.close()
43 lock.release()
44
45 def init(l):
46 global lock
47 lock = l
48
49 # 传入爬取链接,运行函数;
50 def main(offset):
51 url = "https://maoyan.com/board/4?offset=" + str(offset)
52 headers = {
53 "User-Agent": "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36"
54 }
55 html = get_one_page(url, headers=headers)
56 for item in parse_one_page(html):
57 write_to_file(item)
58
59 if __name__ == '__main__':
60 # for i in range(10):
61 # main(i*10)
62 # 使用 进程池 提高爬取速度;
63 lock = Lock()
64 Pool = Pool(initializer=init, initargs=(lock,))
65 Pool.map(main, [i*10 for i in range(10)])

python限定了多进程要调用的函数不能是类方法,需把多进程调用的函数放到类外面,或者变成静态函数。

但静态函数不能被该类的方法调用( self.ProcessWorker  形式),需在外部调用:如 mc = MyClass(), mc.ProcessWorker 或 MyClass().ProcessWorker 。

python 多进程编程中进程池锁共享问题参考博客:https://blog.csdn.net/qq_27292549/article/details/78929296

# 将数组中的每个元素提取出来当作函数的参数,创建一个个进程,放进进程池中;
# 第一个参数是函数,第二个参数是迭代器,将迭代器中的数字作为参数依次传入函数中

最新文章

  1. 沙盒SandBox
  2. php : RBAC 基于角色的用户权限控制-表参考
  3. PNG的使用技巧
  4. android viewpager 图片翻页例子
  5. poj2391 Ombrophobic Bovines 题解
  6. 重学STM32---(七) FSMC+LCD
  7. JNI_Android项目中调用.so动态库实现详解【转】
  8. Python连接Redis连接配置
  9. 前端(各种demo)二:左侧导航栏的折叠和打开(不使用js)基础版和升级版
  10. T-SQL基础(三)之子查询与表表达式
  11. [qemu] qemu从源码编译安装
  12. CentOS 7上安装Pure-FTPd
  13. lvs负载均衡(DR模式)
  14. Python基础【day02】:字符编码(一)
  15. H3C S5120-52P-WiNet交换机配置
  16. mysql主从服务器的配置
  17. BCB 按钮添加背景图
  18. Ambari安装指南
  19. Spring Cloud中,Eureka常见问题总结
  20. NYOJ--520

热门文章

  1. [转]C# 互操作性入门系列(一):C#中互操作性介绍
  2. mysql几种连接方式区别
  3. ArcGIS地形分析--TIN及DEM的生成,TIN的显示
  4. docker实现mysql主从复制
  5. jdbc操作mysql(三):利用注解封装
  6. 基于SigalR实现的奥运会实时金牌榜
  7. Linux centos7 -bash: pstree: 未找到命令
  8. Git使用教程一
  9. .ssh/config 常用配置
  10. 窗口函数至排序——SQLServer2012可高用