0
点赞
收藏
分享

微信扫一扫

Ubuntu-基础工具配置

若如初梘 2024-06-20 阅读 9

在Python中,我们可以使用一些强大的库来编写一个功能强大的爬虫,
Python

首先安装必要的库(如果尚未安装)

pip install requests beautifulsoup4



import requests
from bs4 import BeautifulSoup
import os

def download_images(url, save_dir='images'):
    # 发送GET请求获取网页内容
    response = requests.get(url)
    
    # 检查请求是否成功
    if response.status_code != 200:
        print(f"请求失败: {response.status_code}")
        return
    
    # 使用BeautifulSoup解析HTML
    soup = BeautifulSoup(response.text, 'html.parser')
    
    # 查找所有的img标签,通常包含图片的URL
    img_tags = soup.find_all('img')

    # 保存图片到指定目录
    if not os.path.exists(save_dir):
        os.makedirs(save_dir)

    for img_tag in img_tags:
        img_url = img_tag['src']  # 获取图片链接
        img_name = os.path.join(save_dir, img_url.split('/')[-1])  # 构建文件名

        # 下载图片
        with open(img_name, 'wb') as f:
            img_response = requests.get(img_url, stream=True)
            for chunk in img_response.iter_content(1024):
                f.write(chunk)

    print(f"已下载{len(img_tags)}张图片到'{save_dir}'目录")

使用爬虫

target_url = “http://example.com” # 替换为你想要抓取图片的网站
download_images(target_url)
定义了一个函数download_images,它接受一个URL作为参数,然后找到页面上的所有图片,并将它们下载到指定的目录。为了增强爬虫功能,你可以考虑添加异常处理、代理支持、反爬虫机制、数据提取(如文本、表格等)、以及使用更复杂的库如Scrapy进行更深度的数据抓取。

举报

相关推荐

0 条评论