这段代码可以使用 Python 编译器运行,或者将其保存为 .py 文件并在终端中使用 Python 命令运行。在运行前,需要先安装 requests 和 BeautifulSoup 这两个库。可以通过在终端中输入以下命令进行安装:

pip install requests
pip install beautifulsoup4

然后在终端中进入代码所在目录,并使用以下命令运行:

python 文件名.py

其中,'文件名.py' 应替换为实际保存代码的文件名。运行后,代码会自动获取指定网页中的图片,并保存至 'images' 文件夹中。

代码示例:

import requests
from bs4 import BeautifulSoup

url = 'https://www.acgnoon.com/'
response = requests.get(url)
html = response.text

soup = BeautifulSoup(html, 'html.parser')
img_tags = soup.find_all('img')

for img_tag in img_tags:
    img_url = img_tag.get('src')
    if img_url.endswith('.jpg') or img_url.endswith('.png'):
        img_data = requests.get(img_url).content
        with open('images/' + img_url.split('/')[-1], 'wb') as handler:
            handler.write(img_data)

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

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