【问题标题】:Save downloaded images with python into a local folder使用 python 将下载的图像保存到本地文件夹中
【发布时间】:2020-12-29 16:14:12
【问题描述】:

我使用以下代码从网站上抓取图片网址。我接下来尝试实现的是将以“.jpg”结尾的 url 保存到本地文件夹中,该文件夹可以是 py 代码的位置。 我设法抓取和访问网址并在该位置创建一个文件夹,但我不知道如何保存它们。 这是我的代码,任何想法都非常感谢

from selenium import webdriver
import requests
import os
from bs4 import BeautifulSoup
import urllib
import urllib.request
from urllib.request import urlretrieve
import sys

if sys.version_info[0] >= 3:

from urllib.request import urlretrieve
else:
# if Not Python 3
from urllib import urlretrieve

site = 'https://www.amazon.de/dp/B077S8N26F'
directory = os.path.dirname(os.path.realpath(__file__)) + '/image_folder/'
if not os.path.exists(directory):
    os.makedirs(directory)

driver = webdriver.Chrome()
driver.get(site)
soup = BeautifulSoup(driver.page_source, 'html.parser')

img_tags = soup.find_all('img')
urls = [img['src'] for img in img_tags]
for url in urls:
print(url)
#only the links that end with .jpg
images = [im for im in urls if im.endswith(".jpg")]
print(images)
for im in images:
   #here is the missing part that saves urls into the folder created

【问题讨论】:

    标签: python beautifulsoup save


    【解决方案1】:

    对于images 中的每个条目,这将是图像文件的 URI/URL。

    要获取图像,您需要发出单独的 HTTP 请求来获取它。你可以用python-requests来做到这一点

    这个现有的答案应该可以帮助您,无需重复:How to download image using requests

    【讨论】:

      猜你喜欢
      • 2015-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-25
      • 1970-01-01
      • 2021-08-28
      • 2016-03-09
      相关资源
      最近更新 更多