首页 > 解决方案 > 如何从 URL 下载多个图像

问题描述

我正在尝试使以下代码正常工作。我认为这很接近,但我不断收到一个错误,在最后一行显示“解析时意外 EOF”。

import requests
import subprocess
import os
import urllib.request
from bs4 import BeautifulSoup

os.chdir("C:/Users/Excel/Downloads/")

request = requests.get("http://ottofrello.dk/malerierstor.htm")
content = request.content
soup = BeautifulSoup(content, "html.parser")
element = soup.find_all("img")
for img in element:
    urllib.request.urlretrieve("http://ottofrello.dk/" + img.get('src') + "," + img.get('src') + ")"

我正在使用 Python 3.6。

标签: pythonpython-3.x

解决方案


您可能希望将最后一行重写为:

urllib.request.urlretrieve("http://ottofrello.dk/" + img.get('src'), img.get('src'))

当图像路径不仅是文件名,而是实际路径时,您仍然会偶尔出现错误,但您将朝着正确的方向前进,并且可以稍后解决这个问题。


推荐阅读