python批量爬取图片怎么实现

48次阅读
没有评论

共计 845 个字符,预计需要花费 3 分钟才能阅读完成。

要实现批量爬取图片,可以使用 Python 的 requests 库和 BeautifulSoup 库来爬取网页内容,然后使用正则表达式或者其他方法提取出图片的 url,最后使用 requests 库下载图片。

下面是一个基本的示例代码:

import requests
from bs4 import BeautifulSoup
import os

# 定义要爬取的网页 URL
url = 'http://example.com'

# 发送 GET 请求获取网页内容 
response = requests.get(url)
html = response.text

# 创建保存图片的目录 
os.makedirs('images', exist_ok=True)

# 使用 BeautifulSoup 解析网页内容 
soup = BeautifulSoup(html, 'html.parser')

# 查找所有的图片标签 
img_tags = soup.find_all('img')

# 遍历图片标签,获取图片的 URL 并下载 
for img_tag in img_tags:
    img_url = img_tag['src']
    img_name = img_url.split('/')[-1]  # 获取图片文件名 
    img_path = os.path.join('images', img_name)  # 拼接图片保存路径 

    # 发送 GET 请求下载图片 
    img_response = requests.get(img_url)
    with open(img_path, 'wb') as f:
        f.write(img_response.content)
        print(f'Downloaded {img_path}')

这段代码会从指定的网页 URL 中爬取所有的图片,并保存到当前目录下的 "images" 文件夹中。可以根据具体需求适当修改代码。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-16发表,共计845字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)