写一个用进程和协程运行爬虫的案例
时间: 2024-04-04 21:32:47 浏览: 20
下面是一个用进程和协程运行爬虫的案例,爬取豆瓣电影TOP250的电影名称和评分信息:
```python
import requests
import re
from multiprocessing import Process
import asyncio
import aiohttp
# 爬取电影信息的函数
async def get_movie_info(url):
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
html = await response.text()
# 使用正则表达式提取电影名称和评分信息
pattern = re.compile(r'<span class="title">(.*?)</span>.*?<span class="rating_num" property="v:average">(.*?)</span>',re.S)
items = re.findall(pattern, html)
for item in items:
print(item[0] + ' 评分:' + item[1])
# 使用多进程运行爬虫程序
if __name__ == '__main__':
urls = ['https://movie.douban.com/top250?start={}'.format(i) for i in range(0, 250, 25)]
processes = []
for url in urls:
p = Process(target=asyncio.run, args=(get_movie_info(url),))
p.start()
processes.append(p)
for p in processes:
p.join()
```
在这个案例中,我们使用了多进程的方式运行爬虫程序,并在每个进程中使用协程来实现对电影信息的爬取。通过这种方式,我们可以在短时间内快速爬取豆瓣电影TOP250的电影名称和评分信息。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)