|
|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 chenyixin1992 于 2017-1-14 21:05 编辑
在55课中,小甲鱼老师讲到了自己定制opener,视频中他用的是安装opener以覆盖默认opener的方法。现在我自己尝试了用opener.open(url)的方法方法访问whatismyip.com,但总是报错,看提示好像是说超时了。请问是为什么?我自己尝试了用普通的urllib.request.urlopen(url)就没有问题
——————————————————以下是代码————————————————————
import urllib.request
url='http://www.whatismyip.com.tw'
proxy_support=urllib.request.ProxyHandler({'http':'222.162.36.226'})
opener=urllib.request.build_opener(proxy_support)
opener.addheaders=[('User-Agent','Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36')]
response=opener.open(url)
html=response.read().decode('utf-8')
print(html)
———————————————————以下是报错信息——————————————————
Traceback (most recent call last):
File "D:\Python3.3.2\lib\urllib\request.py", line 1248, in do_open
h.request(req.get_method(), req.selector, req.data, headers)
File "D:\Python3.3.2\lib\http\client.py", line 1061, in request
self._send_request(method, url, body, headers)
File "D:\Python3.3.2\lib\http\client.py", line 1099, in _send_request
self.endheaders(body)
File "D:\Python3.3.2\lib\http\client.py", line 1057, in endheaders
self._send_output(message_body)
File "D:\Python3.3.2\lib\http\client.py", line 902, in _send_output
self.send(msg)
File "D:\Python3.3.2\lib\http\client.py", line 840, in send
self.connect()
File "D:\Python3.3.2\lib\http\client.py", line 818, in connect
self.timeout, self.source_address)
File "D:\Python3.3.2\lib\socket.py", line 435, in create_connection
raise err
File "D:\Python3.3.2\lib\socket.py", line 426, in create_connection
sock.connect(sa)
TimeoutError: [WinError 10060] 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\admin\Desktop\proxy_eg.py", line 11, in <module>
response=opener.open(url)
File "D:\Python3.3.2\lib\urllib\request.py", line 469, in open
response = self._open(req, data)
File "D:\Python3.3.2\lib\urllib\request.py", line 487, in _open
'_open', req)
File "D:\Python3.3.2\lib\urllib\request.py", line 447, in _call_chain
result = func(*args)
File "D:\Python3.3.2\lib\urllib\request.py", line 1268, in http_open
return self.do_open(http.client.HTTPConnection, req)
File "D:\Python3.3.2\lib\urllib\request.py", line 1251, in do_open
raise URLError(err)
urllib.error.URLError: <urlopen error [WinError 10060] 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。>
问题并不在于自定义的 opener, 而是你使用的代理失效了, 去掉代理就正常了
|
|