-1

I started learning Python a couple weeks ago so I could make this project that saves all the images on multiple webpages. Everything works smoothly except the last lines, I get an error that says:

File "/Users/hitchhiker/Desktop/manga_yoinker/main.py", line 36, in <module> with open(filename, "wb") as file: FileNotFoundError: [Errno 2] No such file or directory: 'page/cropped-Jujutsu_kaisen-324x324-1.png'

Here is the code:

import os
import requests
from bs4 import BeautifulSoup
import shutil

link = "https://kaisenscans.com/chapter/jujutsu-kaisen-chapter-"

main_dir = os.path.join("/Volumes/flash", "main_folder")
os.mkdir(main_dir)

for chapter_number in range(1, 2):
    chapter = link + str(chapter_number)
    page = requests.get(chapter)
    chname = "chapter"+str(chapter_number)

current_dir = "/Users/hitchhiker/Desktop/manga_yoinker/" + chname
destination = "/Volumes/flash/main_folder"

dire = os.mkdir(chname)

shutil.move(current_dir, main_dir)

soup = BeautifulSoup(page.content, "html.parser")
imgs = soup.find_all("img")


for img in imgs:
    img_link = img.attrs.get("src")
    image = requests.get(img_link).content
    filename = "page" + img_link[img_link.rfind("/"):]

    with open(filename, "wb") as file:
        file.write(image)

I've searched on google for a solution but can't seem to find anything fitting my problem.

4

1 Answer 1

0

The explanation is in the error :

FileNotFoundError: [Errno 2] No such file or directory: 'page/cropped-Jujutsu_kaisen-324x324-1.png'

With no more details, I would think that the directory page/ doesn't exist. Can you check this ?

the open() will create the file if it doesn't exist but not the parent directories.

If this is the problem, you can automatically create it like this:

dir = './page/'
os.makedirs(dir, exist_ok=True)
# Equivalent to :
# if (not os.path.isdir(dir)):
#    os.mkdir(dir)
Sign up to request clarification or add additional context in comments.

7 Comments

Or the directory exists but the file cropped-xxx.png doesn't.
@ValentinGoldité But opening with w creates the file...
@ValentinGoldité this code is writing the file, so it doesn't need to exist first.
Instead of an if just do os.makedirs(path, exist_ok=True) see Python create directory error Cannot create a file when that file already exists
I checked and it doesn't, but I thought the with open command would create it. Do you know how I can fix this?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.