Python 并发爬虫实用工具 tomorrow 实用解析
本文介绍如何使用 Python 第三方库 tomorrow 实现简单的并发爬虫。通过对比串行与并发请求获取电影网站标题的耗时,展示 threads 装饰器的用法。文章包含安装步骤、完整代码示例及性能测试结果,并给出并发数设置的优化建议。
安装依赖库
在开始之前,需要安装三个关键的 Python 第三方包:用于网络请求的 requests_html,用于生成随机 User-Agent 的 fake-useragent,以及实现并发功能的 tomorrow。
pip install requests_html #网络请求包
pip install fake-useragent #获取useragent包
pip install tomorrow核心实现原理
tomorrow 是一个轻量级的 Python 模块,其核心功能是通过 @threads 装饰器将普通函数转换为支持多线程执行的函数。括号内的数字参数指定了并发线程的数量。通过这种方式,可以在不修改原有函数逻辑的前提下,实现异步并发请求的效果。
完整代码示例
以下代码展示了如何配置会话、定义串行与并发请求函数,并对比两者的执行效率。代码中使用了 requests_html 的 HTMLSession 来保持连接,并通过 fake-useragent 模拟浏览器请求头。
import time
from requests_html import HTMLSession
from fake_useragent import UserAgent as ua
from tomorrow import threads
headers = {"User-Agent": ua().Chrome}
session = HTMLSession()
url_list = ["https://movie.douban.com",
"http://www.1905.com/",
"http://www.mtime.com/",
"https://www.dy2018.com/",
"http://dytt8.net",
"https://www.piaohua.com/",
"http://maoyan.com",
"https://www.xigua110.com/",
"https://www.vmovier.com/",
"http://movie.kankan.com/",
"https://107cine.com/",
"http://movie.youku.com",
"http://film.qq.com",
"http://film.spider.com.cn",
"https://dianying.taobao.com/",
"http://www.wandafilm.com/",
"http://www.dygang.net/",
"http://www.bale.cn/",
"http://dianying.2345.com/",
"http://v.x2y4.com/"]
def get_req(url, timeout=10):
req = session.get(url, headers=headers, timeout=timeout)
if req.status_code == 200:
return req
@threads(5)
def async_get_req(url, timeout=10):
req = session.get(url, headers=headers, timeout=timeout)
if req.status_code == 200:
return req
def get_xpath(req, xpath_str):
return req.html.xpath(xpath_str)[0].strip().replace("\n", "")
start=time.time()
for i in url_list:
print(get_xpath(get_req(i),"//title//text()"))
end=time.time()
print("普通方式花费时间",end-start)
start2 = time.time()
req_list = []
for url in url_list:
req = async_get_req(url)
req_list.append(req)
for req in req_list:
print(get_xpath(req, "//title//text()"))
end2 = time.time()
print("并发后花费时间", end2 - start2)性能对比与优化建议
通过运行上述代码,可以观察到串行请求与并发请求在耗时上的显著差异。测试结果显示,串行方式通常需要 8-9 秒才能完成 20 个网站的访问,而并发方式仅需 2-3 秒左右。
第一次:
普通方式花费时间 7.883908271789551
并发后花费时间 2.2888755798339844
第二次:
普通方式花费时间 8.522203207015991
并发后花费时间 2.4674007892608643
第三次:
普通方式花费时间 9.062756061553955
并发后花费时间 2.8703203201293945尽管并发能显著提升速度,但并发数并非越多越好。过高的并发数可能导致目标服务器拒绝服务或本地网络资源耗尽。建议将并发数设置在 5 到 10 之间,具体最佳数值需根据实际网络带宽和目标网站的承受能力进行调整。
以上就是 Python 并发爬虫实用工具 tomorrow 实用解析的详细内容,更多关于 Python 爬虫优化与并发编程的资料请关注本站其它相关文章!
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









