import requestsfrom bs4 import BeautifulSoupimport urllibdef download_imageurl filename response = requestsgeturl stream=True with openfilename wb as file for chunk in responseiter_conten
要更改代码以获取你想要的图片,你需要检查网页的HTML结构并找到包含你想要的图片的元素。然后,你可以使用BeautifulSoup库中的相应方法来提取这些元素。
以下是修改后的代码示例:
import requests
from bs4 import BeautifulSoup
import urllib
def download_image(url, filename):
response = requests.get(url, stream=True)
with open(filename, 'wb') as file:
for chunk in response.iter_content(1024):
file.write(chunk)
def scrape_images(url):
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
image_tags = soup.find_all('img')
for img in image_tags:
img_url = img.get('src')
if img_url:
if 'your_desired_image_keyword' in img_url: # 替换为你想要的图片的关键字或URL片段
filename = img_url.split('/')[-1]
try:
print(f"Downloading image: {filename}")
download_image(img_url, filename)
except:
print(f"Failed to download image: {filename}")
if __name__ == '__main__':
url = 'https://wallspic.com/cn'
scrape_images(url)
在上述代码中,你需要将your_desired_image_keyword替换为你想要的图片的关键字或URL片段。这将确保只下载包含该关键字的图片。
原文地址: https://www.cveoy.top/t/topic/ie3a 著作权归作者所有。请勿转载和采集!