![](/img/trans.png)
[英]Web scraping: HTTPError: HTTP Error 403: Forbidden, python3
[英]Web Scraping Error (HTTP Error 403: Forbidden)
我正在嘗試制作一個簡單的程序,它獲取網站上的所有圖像地址,然后將它們下載到一個文件夾中。 問題是我收到了 403 錯誤。 我一直試圖修復它一個多小時,迫切需要幫助。 這是我的代碼:
import urllib.request
import requests
from bs4 import BeautifulSoup
url = 'https://www.webtoons.com/en/slice-of-life/how-to-love/ep-100-happy-ending-last-episode/viewer?title_no=472&episode_no=100'
data = requests.get(url)
code = BeautifulSoup(data.text, 'html.parser')
photos = []
def dl_jpg(url, filePath, fileName):
fullPath = filePath + fileName + '.jpg'
urllib.request.urlretrieve(url, fullPath)
for img in code.find('div', id='_imageList'):
pic = str(img)[43:147]
photos.append(str(pic))
for photo in photos:
if photo == '':
photos.remove(photo)
for photo in photos[0:-4]:
dl_jpg(photo, 'images/', 'img')
網站通常會阻止沒有用戶代理的請求。 我更新了您的代碼以隨請求一起發送用戶代理。 我還選擇只使用requests
庫並urllib
。 雖然urllib
確實支持更改的標頭,但您已經在使用requests
而我對它更熟悉。
我還建議在請求之間添加延遲/睡眠,30-45 秒是一個很好的數量。 這將避免向網站發送垃圾郵件和創建拒絕服務。 如果您發送太多太快,某些網站也會阻止您的請求。
import requests
from bs4 import BeautifulSoup
user_agent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.37"
url = 'https://www.webtoons.com/en/slice-of-life/how-to-love/ep-100-happy-ending-last-episode/viewer?title_no=472&episode_no=100'
data = requests.get(url, headers={'User-Agent': user_agent})
code = BeautifulSoup(data.text, 'html.parser')
photos = []
def dl_jpg(url, filePath, fileName):
fullPath = filePath + fileName + '.jpg'
# make request with user-agent. If request is successful then save the result.
image_request = requests.get(url, headers={'User-Agent': user_agent})
if image_request.status_code == 200:
with open(fullPath, 'wb') as f:
f.write(image_request.content)
for img in code.find('div', id='_imageList'):
pic = str(img)[43:147]
photos.append(str(pic))
for photo in photos:
if photo == '':
photos.remove(photo)
for photo in photos[0:-4]:
dl_jpg(photo, 'images/', 'img')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.