猿问

urllib.error.HTTPError:HTTP 错误 404:

我正在尝试从 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但找不到任何帮助。


任何帮助表示赞赏。


慕妹3242003
浏览 611回答 1
1回答

HUX布斯

我想这就是你想要的:import urllibuser_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,}&nbsp;URL = "http://metacritic.com/" + textrequest=urllib.request.Request(URL,None,headers)try:&nbsp; &nbsp; response = urllib.request.urlopen(request)&nbsp; &nbsp; data = response.read()&nbsp; &nbsp; soup = BeautifulSoup(data,'html.parser')&nbsp; &nbsp; metacritic_rating = "Metascore: " + soup.find("span",class_="metascore_w").get_text()&nbsp; &nbsp; send_message(metacritic_rating,chat)&nbsp;except urllib.error.HTTPError as err:&nbsp; &nbsp; #print(err.code)&nbsp; &nbsp; if err.code == 403:&nbsp; &nbsp; &nbsp; &nbsp; <do something>&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; pass输出:403
随时随地看视频慕课网APP

相关分类

Python
我要回答