我正试图打开并解析一个html页面。在Python2.7.8中,我没有问题:
import urllib
url = "https://ipdb.at/ip/66.196.116.112"
html = urllib.urlopen(url).read()
一切都很好。但是我想转到Python3.4,在那里我得到了HTTP错误403(禁止)。我的代码:
import urllib.request
html = urllib.request.urlopen(url) # same URL as before
File "C:\Python34\lib\urllib\request.py", line 153, in urlopen
return opener.open(url, data, timeout)
File "C:\Python34\lib\urllib\request.py", line 461, in open
response = meth(req, response)
File "C:\Python34\lib\urllib\request.py", line 574, in http_response
'http', request, response, code, msg, hdrs)
File "C:\Python34\lib\urllib\request.py", line 499, in error
return self._call_chain(*args)
File "C:\Python34\lib\urllib\request.py", line 433, in _call_chain
result = func(*args)
File "C:\Python34\lib\urllib\request.py", line 582, in http_error_default
raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 403: Forbidden
它适用于其他不使用https的url。
url = 'http://www.stopforumspam.com/ipcheck/212.91.188.166'
没关系。
以下是我在学习python-3时收集到的一些笔记:
我留着它们,以防它们能派上用场或帮助别人。
如何导入
urllib.request
和urllib.parse
:如何发出GET请求:
如何发出POST请求:
如何发出POST请求(
403 forbidden
响应):如何发出GET请求(
403 forbidden
响应):网站似乎不喜欢Python3.x的用户代理
指定
User-Agent
将解决您的问题:注意Python 2.x urllib版本也接收403状态,但与Python 2.x urllib2和Python 3.x urllib不同,它不会引发异常。
您可以通过以下代码确认:
相关问题 更多 >
编程相关推荐