【问题标题】:Downloading/webscraping images from python从 python 下载/网络抓取图像
【发布时间】:2019-09-03 21:15:28
【问题描述】:

我正在尝试从网站下载所有图像,但无法下载。如何从网站的特定部分下载所有图像并将其保存到我的目录?

下面的代码导出所有图像并将图像链接保存到 csv 文件,但我也希望图像也保存在我的目录中。

from urllib.request import Request, urlopen
from bs4 import BeautifulSoup as soup

my_url = 'https://www.newegg.com/Video-Cards-Video-Devices/Category/ID-38?Tpk=graphics%20card'

req = Request(my_url, headers={'User-Agent': 'Mozilla/5.0'})


webpage = urlopen(req).read()
page_soup = soup(webpage, "html.parser")


filename = "abc.csv"
f = open(filename, "w")


headers = "imagelink\n" 
f.write(headers)


snackcrisps = page_soup.findAll("div",{"class":"divCategories divShops-newegg"})
crispitem = snackcrisps[0]


img = crispitem.findAll("div",{"class":"product_image_div productSmall_image_div_lit"})
img1 = img[0]


for img1 in img:

    img2 = img1.findAll('img')
    imageLink = img2[0].get('src')


    print("imageLink: " + imageLink)

    f.write(imageLink + "\n")

f.close()

如何将图像保存在本地目录中?需要帮助!!

非常感谢

【问题讨论】:

标签: python-3.x beautifulsoup


【解决方案1】:

我使用对this post 的回复来制定我的答案。

首先,您需要为您想要的图像构建完整的 URL。这可以简单到将“https:”附加到图像链接的开头,或者根本不更改值。您必须调查(查看此post)如何根据它们是相对还是绝对来调整您找到的 URL。

您需要使用requests 模块来发出图像请求。

import requests
import shutil

for img1 in img:

    img2 = img1.findAll('img')
    imageLink = img2[0].get('src')
    if not "https:" in imageLink:
        imageLink = "https:" + imageLink

    r = requests.get(imageLink, stream=True)
    if r.response = 200:
        with open("my_file.jpg", 'wb') as f:
            r.raw.decode_content = True
            shutil.copyfileobj(r.raw, f)

【讨论】:

    猜你喜欢
    • 2014-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-02
    相关资源
    最近更新 更多