Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 404使用urllib时出错,但URL在浏览器中工作正常,错误中返回整个网页_Python 3.x_Http Status Code 404_Urllib - Fatal编程技术网

Python 3.x 404使用urllib时出错,但URL在浏览器中工作正常,错误中返回整个网页

Python 3.x 404使用urllib时出错,但URL在浏览器中工作正常,错误中返回整个网页,python-3.x,http-status-code-404,urllib,Python 3.x,Http Status Code 404,Urllib,我正在尝试使用urllib用python打开一个web页面(来刮取它)。该网页在浏览器中看起来不错,但我在urlopen中遇到了404错误。但是,如果查看随错误返回的文本,它实际上包含完整的网页 from urllib.request import Request, urlopen from urllib.error import HTTPError, URLError from bs4 import BeautifulSoup try: htm

我正在尝试使用urllib用python打开一个web页面(来刮取它)。该网页在浏览器中看起来不错,但我在urlopen中遇到了404错误。但是,如果查看随错误返回的文本,它实际上包含完整的网页

    from urllib.request import Request, urlopen
    from urllib.error import HTTPError, URLError
    from bs4 import BeautifulSoup

    try:
        html = urlopen('http://www.enduroworldseries.com/series-rankings')
    except HTTPError as e:
        err = e.read()
        code = e.getcode()
        print(err)
当我运行代码时,异常被捕获,“代码”是“404”。err变量具有完整的html,当您在浏览器中查看页面时会显示该html。那我为什么会出错呢


不确定这是否重要,但同一域上的其他页面可以使用urlopen正常加载

我在不知道最初的问题是什么的情况下找到了解决方案。只需将
urllib
替换为
requests
库即可

req = Request('http://www.enduroworldseries.com/series-rankings', headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36'})
html = urlopen(req)
bsObj = BeautifulSoup(html, "html.parser")
变成

response = requests.get('http://www.enduroworldseries.com/series-rankings', {'User-Agent': 'Mozilla/5.0'})
bsObj = BeautifulSoup(response.content, "html.parser")

我在不知道最初的问题是什么的情况下找到了解决方案。只需将
urllib
替换为
requests
库即可

req = Request('http://www.enduroworldseries.com/series-rankings', headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36'})
html = urlopen(req)
bsObj = BeautifulSoup(html, "html.parser")
变成

response = requests.get('http://www.enduroworldseries.com/series-rankings', {'User-Agent': 'Mozilla/5.0'})
bsObj = BeautifulSoup(response.content, "html.parser")

当您访问该页面时,该资源“”的提供程序将返回404。这可能是一种阻止人们使用像您这样的代码访问/刮取页面的方法。您可能需要研究如何正确准备您的用户代理等等,因此看起来您是从浏览器而不是代码访问页面。我已尝试将“用户代理”设置为“Mozilla/5.0(Windows NT 10.0;Win64;x64)AppleWebKit/537.36(KHTML,类似Gecko)Chrome/59.0.3071.115 Safari/537.36”)。没有帮助。当您访问该页面时,该资源“”的提供程序将返回404。这可能是一种阻止人们使用像您这样的代码访问/刮取页面的方法。您可能需要研究如何正确准备您的用户代理等等,因此看起来您是从浏览器而不是代码访问页面。我已尝试将“用户代理”设置为“Mozilla/5.0(Windows NT 10.0;Win64;x64)AppleWebKit/537.36(KHTML,类似Gecko)Chrome/59.0.3071.115 Safari/537.36”)。没有帮助。