如何从网站下载图像并创建文件夹并将图像放入文件夹

时间:2020-06-13 18:47:11

标签: python web-scraping urlretrieve

这些天,我正在尝试编写具有以下功能的代码 1.从网站下载图片 2.制作一个以标题命名的文件夹 3.并将图像放入新创建的文件夹中。

仅供参考,我正在考虑下载许多图像,因此我将图像名称设置为n。

这是我编写的代码

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

url = "https://www.sciencemag.org/news/2019/11/here-s-better-way-convert-dog-years-human-years-scientists-say"
req = requests.get(url)
html = req.text
soup = BeautifulSoup(html,"html.parser")

#getting title, name for directory
title = soup.select_one(".article__headline").get_text()

#downloading img
dog = soup.select_one(".figure__head")
imgUrl = dog.find("img")['src']

#making directory naming after title
path = 'C:/{}'.format(title)
if not os.path.isdir(path):
    os.mkdir(path)

#put the image into the newly made directory
n = 1
urlretrieve(imgUrl,path+str(n)+".jpg")

我想将图像放入“ path”目录,但结果是创建了一个以 标题带有相同名称的图像文件。

如何获得想要的结果?

如果有任何异常或异常的界线,或者有更好的方法,请随时告诉我。

1 个答案:

答案 0 :(得分:0)

我认为您想念路径分隔符'/'

>>> title = 'human'
>>> n = 1
>>> path = 'C:/{}'.format(title)
>>> print(path+str(n)+".jpg")
C:/human1.jpg

应该是

>>> print(path+'/'+str(n)+".jpg")
C:/human/1.jpg