引发HTTPError(req.full_url,code,msg,hdrs,fp)urllib.error.HTTPError:HTTP错误403:禁止

时间:2018-11-01 15:59:55

标签: python urllib

漫画(日语漫画)不是pdf格式,而是原始图像,因此我创建了一个可自动下载照片的工具。

这是我的代码

import requests
import urllib.request
from bs4 import BeautifulSoup

responsePage = input("Enter URL: ")
response = requests.get(responsePage)

soup = BeautifulSoup(response.text, 'html.parser')
images = soup.findAll('img')

image_name = 0

for img in images[1:-1]:
    image_name += 1
    url = img['src']
    full_name = str(image_name) + '.jpg'
    print(response.headers)
    resource_image = urllib.request.urlretrieve(url, full_name)
    print(full_name + " Saved!")

我收到的错误是:

urllib.error.HTTPError: HTTP Error 403: Forbidden

关于如何解决此问题的任何建议? 帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

import requests
from bs4 import BeautifulSoup
import os

def download_image(url, path):
    r = requests.get(url, stream=True)
    if r.status_code == 200:
        with open(path, 'wb') as f:
            for chunk in r:
                f.write(chunk)

URL = "https://manganelo.com/chapter/read_detective_conan_manga_online_free/chapter_10"
r = requests.get(URL)

soup = BeautifulSoup(r.text, 'html.parser')
images = soup.findAll('img')
for i in images:
    url = i.attrs["src"]
    os.makedirs(url.split('/')[-2], exist_ok=True)
    download_image(url, os.path.join(url.split('/')[-2], url.split('/')[-1]))