簡體   English   中英

Python urllib.request.urlopen()返回錯誤403

[英]Python urllib.request.urlopen() returning error 403

我正在嘗試下載頁面的HTML(在這種情況下為http://www.guangxindai.com ),但我又收到了錯誤403。這是我的代碼:

import urllib.request
opener = urllib.request.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
f = opener.open("http://www.guangxindai.com")
f.read()

但是我得到了錯誤響應。

Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    f = opener.open("http://www.guangxindai.com")
  File "C:\Python33\lib\urllib\request.py", line 475, in open
    response = meth(req, response)
  File "C:\Python33\lib\urllib\request.py", line 587, in http_response
    'http', request, response, code, msg, hdrs)
  File "C:\Python33\lib\urllib\request.py", line 513, in error
    return self._call_chain(*args)
  File "C:\Python33\lib\urllib\request.py", line 447, in _call_chain
    result = func(*args)
  File "C:\Python33\lib\urllib\request.py", line 595, in http_error_default
    raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 403: Forbidden

我嘗試了不同的請求標頭,但仍然無法獲得正確的響應。 我可以通過瀏覽器查看網絡。 對我來說似乎很奇怪。 我猜想網絡使用某種方法來阻止網絡蜘蛛。 有人知道發生了什么嗎? 如何正確獲取頁面的HTML?

我遇到了與您和我在此鏈接中找到答案的相同問題。

Stefano Sanfilippo提供的答案非常簡單,對我有用

from urllib.request import Request, urlopen

url_request = Request("http://www.guangxindai.com", 
                      headers={"User-Agent": "Mozilla/5.0"})
webpage = urlopen(url_request).read()

如果您的目的是閱讀頁面的html,則可以使用以下代碼。 它在Python 2.7上對我有用

import urllib
f = urllib.urlopen("http://www.guangxindai.com")
f.read()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM