爬虫多线程高效高速爬取图片
6.23 自我总结
爬虫多线程高效高速爬取图片
基于之前的爬取代码我们进行函数的封装并且加入多线程
之前的代码https://www.cnblogs.com/pythonywy/p/11066842.html
from concurrent import futures
导入的模块
ex = futures.ThreadPoolExecutor(max_workers =22) #设置线程个数
ex.submit(方法,方法需要传入的参数)
复制import os
import requests
from lxml.html import etree
from concurrent import futures #多线程
url = 'http://www.doutula.com/'
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36',}
def img_url_lis(url):
response = requests.get(url,headers = headers)
response.encoding = 'utf8'
response_html = etree.HTML(response.text)
img_url_lis = response_html.xpath('.//img/@data-original')
return img_url_lis
#创建图片文件夹
img_file_path = os.path.join(os.path.dirname(__file__),'img')
if not os.path.exists(img_file_path): # 没有文件夹名创建文件夹
os.mkdir(img_file_path)
print(img_file_path)
def dump_one_img(url):
name = str(url).split('/')[-1]
response = requests.get(url, headers=headers)
img_path = os.path.join(img_file_path, name)
with open(img_path, 'wb') as fw:
fw.write(response.content)
def dump_imgs(urls:list):
for url in urls:
ex = futures.ThreadPoolExecutor(max_workers =22) #多线程
ex.submit(dump_one_img,url) #方法,对象
# dump_one_img(url)
def run():
count = 1
while True:
if count == 10:
count += 1
continue
lis = img_url_lis(f'http://www.doutula.com/article/list/?page={count}')
if len(lis) == 0:
print(count)
break
dump_imgs(lis)
print(f'第{count}页也就完成')
count +=1
if __name__ == '__main__':
run()
可以更加快速的爬取多个内容
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理