Python crawler web page image download to local

You can use Python's requests library to obtain the source code of a web page, use the BeautifulSoup library to parse HTML, and use the urllib library to download images to your local computer. Here is a sample code:

import requests from bs4 import BeautifulSoup import urllib 
# 获取网页源码 
url = 'https://example.com' 
# 替换成您要获取源码的网页
URL response = requests.get(url) 
html = response.text 
# 解析图片地址
 soup = BeautifulSoup(html, 'html.parser') 
image_tags = soup.find_all('img')
 image_urls = [tag['src'] for tag in image_tags]
 # 下载图片到本地 
for i, image_url in enumerate(image_urls): try: urllib.request.urlretrieve(image_url, f'image_{i+1}.jpg')
 # 图片将保存为'image_1.jpg', 'image_2.jpg'等
 print(f'成功下载图片{i+1}')
 except Exception as e: print(f'下载图片{i+1}时出错:{e}') 

Please note that the URL and file name in the above code are examples and you need to replace them according to the actual situation. In addition, this code can only download files with image type JPEG. If you want to download images in other formats, you need to make corresponding modifications.

Guess you like

Origin blog.csdn.net/qq_25462179/article/details/132469766