Python 批量下载 VCG 网站图片 - 使用 requests 和 BeautifulSoup
Python 批量下载 VCG 网站图片
本代码使用 Python 的 requests 和 BeautifulSoup 库从 VCG 网站批量下载图片,并使用多线程加速下载速度,代码包含错误处理机制,并提供详细的注释说明。
import requests
from bs4 import BeautifulSoup
import os
import threading
# 网页链接
url = 'https://www.vcg.com/creative/817368554'
# 获取网页内容
try:
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
except Exception as e:
print(f'获取网页内容出错:{e}')
exit()
# 获取所有图片标签
img_tags = soup.find_all('img')
# 创建文件夹(如果不存在)
folder_path = 'D:/pt'
if not os.path.exists(folder_path):
os.makedirs(folder_path)
# 去重集合
url_set = set()
# 下载图片函数
def download_img(img_url, file_path):
try:
img_data = requests.get(img_url).content
with open(file_path, 'wb') as f:
f.write(img_data)
except Exception as e:
print(f'下载图片 {img_url} 出错:{e}')
# 遍历所有图片标签,获取图片 URL,并保存到本地
threads = []
for img in img_tags:
img_url = img.get('src')
if img_url and 'http' in img_url and img_url not in url_set:
url_set.add(img_url)
file_name = img_url.split('/')[-1]
file_path = os.path.join(folder_path, file_name)
thread = threading.Thread(target=download_img, args=(img_url, file_path))
threads.append(thread)
thread.start()
# 等待所有线程结束
for thread in threads:
thread.join()
代码说明:
- 使用
requests库获取网页内容,使用BeautifulSoup库解析网页 HTML 结构。 - 遍历所有图片标签,获取图片 URL,并使用多线程下载图片。
- 使用
set数据结构对图片 URL 进行去重,避免重复下载。 - 使用
threading库实现多线程下载,提高下载速度。 - 使用
try...except代码块处理下载过程中的错误。
注意:
- 请根据实际情况修改代码中的
url和folder_path变量。 - 本代码仅供参考,实际使用过程中可能需要根据具体情况进行修改。
原文地址: https://www.cveoy.top/t/topic/n23r 著作权归作者所有。请勿转载和采集!