我想把电影的收视率从元批评中抹去。下面是代码中抛出错误的部分。

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的所有答案,但找不到任何帮助。
如有任何帮助,我们将不胜感激。

最佳答案

我想这就是你想要的:

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

09-25 16:08