第八天——多任务异步爬虫
一、异步爬虫概述
爬虫的本质:就是客户端向服务器请求批量获取响应数据。如果有多个待爬取的url的话,只用一个线程切采用串行的方式执行,那么只能等待一个爬虫任务完成之后才能继续下一个爬虫任务,这样的话效率是非常低的。
所以,在我们心中其实很自然的就可以想到使用异步机制来提高爬虫的速度。通过构建进程池或者线程池来完成异步爬虫,即使用多进程或多线程来处理多个请求,当别的进程或线程发生阻塞时,自动切换到另一进程或线程执行下一个爬虫任务。
高性能异步爬虫的目的:在爬虫中使用异步实现高性能的数据爬取操作。
注意:python中无法实现真正的多线程,因为其并不能充分利用多核CPU资源。如果想要充分利用CPU资源的话大部分情况下都是使用的多进程(multiprocessing)
import requests
import time
t1 = time.time()
urls = ['https://scpic1.chinaz.net/Files/pic/pic9/202201/hpic4949_s.jpg',
'https://scpic.chinaz.net/Files/pic/pic9/202201/hpic4950_s.jpg',
'https://scpic1.chinaz.net/Files/pic/pic9/202201/hpic4948_s.jpg',
'https://scpic2.chinaz.net/Files/pic/pic9/202201/apic37939_s.jpg',
'https://scpic3.chinaz.net/Files/pic/pic9/202201/apic37931_s.jpg',
'https://scpic3.chinaz.net/Files/pic/pic9/202201/apic37934_s.jpg',
'https://scpic.chinaz.net/Files/pic/pic9/202201/apic37936_s.jpg']
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36'}
def get_content(url):
print('正在爬取', url)
response = requests.get(url, headers=headers)
if response.status_code == 200:
return response.content
def parse_content(content):
print('响应数据长度为为:',len(content))
for url in urls:
content = get_content(url)
parse_content(content)
t2 = time.time()
print('程序总用时为:', t2-t1)
二、异步爬虫的方式
2.1 多线程、多进程(不推荐)
-
优点:可以为相关阻塞的操作开启线程或者进程,阻塞操作就可以异步执行。
-
缺点:不能够无限制的开启多进程或者多线程
爬虫程序模拟(单线程):
import time t1 = time.time() lst = [] urls = [1, 2, 3, 4, 5, 6, 7, 8, 9] result = [] def GetResponse(url): global result time.sleep(2) r = url * url result.append(r) if __name__ == '__main__': for url in urls: GetResponse(url) t2 = time.time() print(result) print('消耗时间:', t2-t1)
爬虫程序模拟(异步,多进程使用):
import time import multiprocessing t1 = time.time() lst = [] urls = [1, 2, 3, 4, 5, 6, 7, 8, 9] result = [] def GetResponse(url, queue): time.sleep(