Python爬虫: 使用BeautifulSoup从网站抓取图片并保存

本文将提供一个Python代码示例,演示如何使用requestsBeautifulSoup库从网站抓取图片并保存到本地。

代码示例:

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)

代码解析:

  1. 导入必要的库: requests用于发送网络请求,BeautifulSoup用于解析HTML内容,urllib用于处理URL。
  2. download_image 函数: 该函数接收图片URL和保存文件名作为参数,使用requests库下载图片并保存到指定文件。
  3. scrape_images 函数: 该函数接收网站URL作为参数,使用requests库获取网页内容,并使用BeautifulSoup解析HTML结构。它查找所有<img>标签,提取图片URL,并根据条件筛选所需的图片进行下载。
  4. 筛选图片: 代码示例中使用if 'your_desired_image_keyword' in img_url来筛选图片,你需要将'your_desired_image_keyword'替换为你想要下载的图片的关键字或URL片段。
  5. 主程序: 主程序设置目标网站URL,并调用scrape_images函数进行抓取。

注意:

  • 为了正确地获取你想要的图片,你需要查看目标网站的HTML结构,找到包含所需图片的<img>标签,并根据其属性(如srcalt等)进行筛选。
  • 在使用这个代码示例之前,请务必阅读目标网站的使用条款,确保你的爬虫行为符合其规定。

希望这个代码示例能够帮助你从网站抓取图片并保存到本地。

Python爬虫: 使用BeautifulSoup从网站抓取图片并保存

原文地址: https://www.cveoy.top/t/topic/fRl2 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录