-1

These days I am trying to make a code with functions of 1. to download an image from a website 2. to make a folder named after its title 3. and put the image into the newly made folder.

FYI, I am considering download many images so I set n for the image's name.

This is the code that I wrote

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")

I wanted to put the image into "path" directory, but the result was making a file named after the title with a image file with same name.

How can I get the result that I want?

and if there are any wierd or abnomal lines, or if there are better ways, please do not hesitate to tell me.

Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
ppooppoo
  • 13
  • 4

1 Answers1

0

I think you miss the path seperator '/'

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

It should be

>>> print(path+'/'+str(n)+".jpg")
C:/human/1.jpg
Jason Yang
  • 11,284
  • 2
  • 9
  • 23