你可以使用Python的requests库来发起HTTP请求,并使用BeautifulSoup库来解析HTML文档以获取图片的URL。
下面是一个简单的示例代码,用于批量爬取网页上的图片:
import requestsfrom bs4 import BeautifulSoupimport osdef download_image(url, save_dir):response = requests.get(url)filename = url.split("/")[-1]filepath = os.path.join(save_dir, filename)with open(filepath, "wb") as f:f.write(response.content)print(f"Downloaded {url} to {filepath}")def get_image_urls(url):response = requests.get(url)soup = BeautifulSoup(response.text, "html.parser")img_tags = soup.find_all("img")img_urls = [img["src"] for img in img_tags]return img_urlsdef batch_download_images(url, save_dir):img_urls = get_image_urls(url)for img_url in img_urls:if not img_url.startswith("http"):img_url = url + img_url # 拼接相对路径download_image(img_url, save_dir)url = "https://example.com" # 要爬取图片的网页save_dir = "images" # 图片保存的目录batch_download_images(url, save_dir)在代码中,get_image_urls函数用于获取网页上的所有图片URL,download_image函数用于下载图片,batch_download_images函数用于批量下载图片。
你需要将url变量设置为要爬取图片的网页的URL,将save_dir变量设置为图片保存的目录。然后运行batch_download_images函数即可开始批量爬取网页图片。
请注意,这只是一个简单的示例,实际中可能需要根据具体情况进行修改和完善。另外,爬取网页图片涉及到版权和合法问题,请确保你有权利或合法使用这些图片。