python高性能异步爬虫
发布时间:2022-12-14 14:43:07 280 相关标签: # python# 爬虫# apache# 数据
目的:
在爬虫中使用异步实现高性能的数据爬取操作。
异步爬虫的方式:
1、多线程,多进程(不建议):
好处:可以为相关阻塞的操作单独开启线程,阻塞操作就可以异步执行。
弊端:无法无限制的开启多线程或者多进程。
2、线程池、进程池(适当的使用):
好处:可以降低系统对进程或者线程创建和销毁的一个频率,从而很好的降低系统的开销。
弊端:池中线程或进程的数量是有上限。
原则:线程池处理的是阻塞且耗时的操作。
不加线程池的操作:
# coding:utf-8
import requests
import time
headers = {
"User-Agent": "Mozilla/5.0(Windows NT 6.1;WOW64) AppleWebKit/537.36(KABUL, like Gecko) "
"Chrome/86.0.4240.198Safari/537.36 "
}
urls = [
'https://mirrors.tuna.tsinghua.edu.cn/apache/accumulo/1.10.2/accumulo-1.10.2-bin.tar.gz',
'https://mirrors.tuna.tsinghua.edu.cn/apache/accumulo/2.1.0/accumulo-2.1.0-bin.tar.gz',
'https://mirrors.tuna.tsinghua.edu.cn/apache/activemq/5.16.5/apache-activemq-5.16.5-bin.zip'
]
def get_content(url):
print("正在获取:", url)
# get方法是一个阻塞的方法
resp = requests.get(url, headers=headers)
if resp.status_code == 200:
return resp.content
def parse_content(content):
print("响应数据的长度为:", len(content))
start_time = time.time()
for url in urls:
content = get_content(url)
parse_content(content)
end_time = time.time()
print('%d second'% (end_time-start_time))

增加线程池的操作:
# coding:utf-8
# coding:utf-8
import requests
import time
from multiprocessing.dummy import Pool
headers = {
"User-Agent": "Mozilla/5.0(Windows NT 6.1;WOW64) AppleWebKit/537.36(KABUL, like Gecko) "
"Chrome/86.0.4240.198Safari/537.36 "
}
urls = [
'https://mirrors.tuna.tsinghua.edu.cn/apache/accumulo/1.10.2/accumulo-1.10.2-bin.tar.gz',
'https://mirrors.tuna.tsinghua.edu.cn/apache/accumulo/2.1.0/accumulo-2.1.0-bin.tar.gz',
'https://mirrors.tuna.tsinghua.edu.cn/apache/activemq/5.16.5/apache-activemq-5.16.5-bin.zip'
]
def get_content(url):
print("正在获取:", url)
# get方法是一个阻塞的方法
resp = requests.get(url, headers=headers)
if resp.status_code == 200:
return resp.content
def parse_content(content):
print("响应数据的长度为:", len(content))
start_time = time.time()
# 实例化一个线程池对象
pool = Pool(3)
# 将列表中的每一个列表元素传递给get_content中进行处理。
pool.map(get_content, urls)
end_time = time.time()
print('%d second'% (end_time-start_time))
pool.close()
pool.join()

线程池的应用:
from multiprocessing.dummy import Pool
urls = [
'https://mirrors.tuna.tsinghua.edu.cn/apache/accumulo/1.10.2/accumulo-1.10.2-bin.tar.gz',
'https://mirrors.tuna.tsinghua.edu.cn/apache/accumulo/2.1.0/accumulo-2.1.0-bin.tar.gz',
'https://mirrors.tuna.tsinghua.edu.cn/apache/activemq/5.16.5/apache-activemq-5.16.5-bin.zip'
]
start_time = time.time()
# 实例化一个线程池对象
pool = Pool(3)
# 将列表中的每一个列表元素传递给get_content中进行处理。
pool.map(get_content, urls)
end_time = time.time()
print('%d second'% (end_time-start_time))
pool.close()
pool.join()
文章来源: https://blog.51cto.com/u_14012524/5928932
特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报