urllib.error.HTTPError:HTTP错误404:从Metacritic中抓取数据时找不到Python

问题描述 投票:1回答:1

我正在试图从Metacritic中删除电影评级。这是抛出错误的代码部分。

text = text.replace("_","-")
user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7'
headers={'User-Agent':user_agent,} 
URL = "http://metacritic.com/" + text
request=urllib.request.Request(URL,None,headers)
try:
    response = urllib.request.urlopen(request)
    data = response.read()
    soup = BeautifulSoup(data,'html.parser')
    metacritic_rating = "Metascore: " + soup.find("span",class_="metascore_w").get_text()
    send_message(metacritic_rating,chat) 
except:
    pass

我用这个修改了我写的:https://stackoverflow.com/a/42441391/8618880

我不能因为这个而使用requests.get()urllib2.HTTPError: HTTP Error 403: Forbidden

我正在寻找一种获取页面状态代码的方法。当我使用requests.get()时,我能找到一种方法。

我查看了所有答案的标题:urllib.error.HTTPError: HTTP Error 404: Not Found Python但找不到任何帮助。

任何帮助表示赞赏。

python http beautifulsoup python-requests http-error
1个回答
1
投票

我想这就是你想要的:

import urllib


user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7'
headers={'User-Agent':user_agent,} 
URL = "http://metacritic.com/" + text
request=urllib.request.Request(URL,None,headers)

try:
    response = urllib.request.urlopen(request)
    data = response.read()
    soup = BeautifulSoup(data,'html.parser')
    metacritic_rating = "Metascore: " + soup.find("span",class_="metascore_w").get_text()
    send_message(metacritic_rating,chat) 
except urllib.error.HTTPError as err:
    #print(err.code)
    if err.code == 403:
        <do something>
    else:
        pass

输出:

403
© www.soinside.com 2019 - 2024. All rights reserved.