以下是一个简单的Python爬取图片的代码:

import requests
from bs4 import BeautifulSoup
import os

# 爬取的网址
url = "https://www.example.com"

# 请求网页
response = requests.get(url)

# 解析网页
soup = BeautifulSoup(response.text, "html.parser")

# 创建目录保存图片
if not os.path.exists("images"):
    os.mkdir("images")

# 爬取图片链接并下载
for img in soup.find_all("img"):
    img_url = img.get("src")
    if img_url.startswith("http"):
        img_response = requests.get(img_url)
        with open("images/" + os.path.basename(img_url), "wb") as f:
            f.write(img_response.content)

这个代码使用了requests库和BeautifulSoup库,先请求网页,然后解析网页,找到所有的img标签,获取图片链接,如果链接是以http开头的就下载保存到images目录下。

用Python写一个爬取图片代码

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

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