这些天我正在尝试制作具有以下功能的代码 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")
我想将图像放入“路径”目录,但结果是制作了一个以标题命名的文件,并带有同名的图像文件。
我怎样才能得到我想要的结果?
如果有任何奇怪或异常的线条,或者是否有更好的方法,请随时告诉我。