【问题标题】:urllib.error.HTTPError: HTTP Error 404: Not Found Python while scraping data from Metacriticurllib.error.HTTPError:HTTP 错误 404:从 Metacritic 抓取数据时未找到 Python
【发布时间】:2019-08-20 03:24:48
【问题描述】:

我正在尝试从 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 的所有答案,但找不到任何帮助。

感谢任何帮助。

【问题讨论】:

  • 那么你到底想要什么?你只是想打印出响应码?
  • 是的。我想将它与 404 进行比较并做一些事情。
  • 如果您发现HTTPError 异常,您可以使用HTTPError.code 获取HTTP 状态。

标签: python http beautifulsoup python-requests http-error


【解决方案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

【讨论】:

    猜你喜欢
    • 2020-11-21
    • 2017-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-30
    • 2021-10-03
    • 2021-04-02
    相关资源
    最近更新 更多