Python:urllib.error.HTTPError:HTTP 错误 404:未找到

新手上路,请多包涵

我写了一个脚本来查找 SO 问题标题中的拼写错误。我用了大约一个月。效果很好。

但是现在,当我尝试运行它时,我得到了这个。

 Traceback (most recent call last):
  File "copyeditor.py", line 32, in <module>
    find_bad_qn(i)
  File "copyeditor.py", line 15, in find_bad_qn
    html = urlopen(url)
  File "/usr/lib/python3.4/urllib/request.py", line 161, in urlopen
    return opener.open(url, data, timeout)
  File "/usr/lib/python3.4/urllib/request.py", line 469, in open
    response = meth(req, response)
  File "/usr/lib/python3.4/urllib/request.py", line 579, in http_response
    'http', request, response, code, msg, hdrs)
  File "/usr/lib/python3.4/urllib/request.py", line 507, in error
    return self._call_chain(*args)
  File "/usr/lib/python3.4/urllib/request.py", line 441, in _call_chain
    result = func(*args)
  File "/usr/lib/python3.4/urllib/request.py", line 587, in http_error_default
    raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 404: Not Found

这是我的代码

import json
from urllib.request import urlopen
from bs4 import BeautifulSoup
from enchant import DictWithPWL
from enchant.checker import SpellChecker

my_dict = DictWithPWL("en_US", pwl="terms.dict")
chkr = SpellChecker(lang=my_dict)
result = []

def find_bad_qn(a):
    url = "https://stackoverflow.com/questions?page=" + str(a) + "&sort=active"
    html = urlopen(url)
    bsObj = BeautifulSoup(html, "html5lib")
    que = bsObj.find_all("div", class_="question-summary")
    for div in que:
        link = div.a.get('href')
        name = div.a.text
        chkr.set_text(name.lower())
        list1 = []
        for err in chkr:
            list1.append(chkr.word)
        if (len(list1) > 1):
            str1 = ' '.join(list1)
            result.append({'link': link, 'name': name, 'words': str1})

print("Please Wait.. it will take some time")
for i in range(298314,298346):
    find_bad_qn(i)
for qn in result:
    qn['link'] = "https://stackoverflow.com" + qn['link']
for qn in result:
    print(qn['link'], " Error Words:", qn['words'])
    url = qn['link']

更新

这是导致问题的网址。即使此网址存在。

https://stackoverflow.com/questions?page=298314&sort=active

我尝试将范围更改为一些较低的值。它现在工作正常。

为什么上面的网址会发生这种情况?

原文由 jophab 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 2.3k
2 个回答

显然,每页默认显示的问题数是 50,因此您在循环中定义的范围超出了每页 50 个问题的可用页数。该范围应调整为不超过每页 50 个问题的总页数。

此代码将捕获 404 错误,这是您收到错误的原因,并忽略它以防万一您超出范围。

 from urllib.request import urlopen

def find_bad_qn(a):
    url = "https://stackoverflow.com/questions?page=" + str(a) + "&sort=active"
    try:
        urlopen(url)
    except:
        pass

print("Please Wait.. it will take some time")
for i in range(298314,298346):
    find_bad_qn(i)

原文由 Atirag 发布,翻译遵循 CC BY-SA 3.0 许可协议

默认的“User-Agent”似乎没有 Mozilla 那样多的访问权限。

尝试导入请求并将 , headers={'User-Agent': 'Mozilla/5.0'} 附加到您的网址末尾。

IE:

 from urllib.request import Request, urlopen
url = f"https://stackoverflow.com/questions?page={str(a)}&sort=active"
req = Request(url, headers={'User-Agent': 'Mozilla/5.0'})
html = urlopen(req)

原文由 Stevo 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题