要使用Python爬虫爬取网页图片,您可以使用第三方库requests和BeautifulSoup。以下是一个简单的示例,说明如何爬取一个网页上的所有图片URL:
pip install requests
pip install beautifulsoup4
web_scraper.py
的Python文件,并在其中编写以下代码:import requests
from bs4 import BeautifulSoup
def get_image_urls(url):
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
image_urls = []
for img in soup.find_all('img'):
img_url = img.get('src')
if img_url:
image_urls.append(img_url)
return image_urls
def download_images(image_urls, save_directory):
if not os.path.exists(save_directory):
os.makedirs(save_directory)
for index, image_url in enumerate(image_urls):
filename = f'image_{index}.jpg'
file_path = os.path.join(save_directory, filename)
response = requests.get(image_url)
with open(file_path, 'wb') as f:
f.write(response.content)
if __name__ == '__main__':
url = input('请输入要爬取的网址:')
save_directory = input('请输入保存图片的目录:')
image_urls = get_image_urls(url)
print(f'找到 {len(image_urls)} 个图片URL。')
download_images(image_urls, save_directory)
print(f'已将图片保存到 {save_directory}。')
注意:这个示例可能无法处理一些特殊情况,例如相对URL、懒加载图片或JavaScript动态加载的图片。您可能需要根据目标网站的具体情况对代码进行调整。