|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
import urllib.request
url = 'http://www.whatismyip.com.tw'
proxy_support = urllib.request.ProxyHandler({'http': '113.123.0.100:3256'}) # 创建一个代理ip
opener = urllib.request.build_opener(proxy_support) # 创建一个opener
urllib.request.build_opener(opener) # 将创建好的apener安装上
response = urllib.request.urlopen(url)
html = response.read().decode('utf-8')
print(html)
这是报错
Traceback (most recent call last):
File "E:/Users/ASUS/Desktop/python/pachong.py", line 5, in <module>
urllib.request.build_opener(opener) # 将创建好的apener安装上
File "F:\python1\lib\urllib\request.py", line 600, in build_opener
opener.add_handler(h)
File "F:\python1\lib\urllib\request.py", line 438, in add_handler
raise TypeError("expected BaseHandler instance, got %r" %
TypeError: expected BaseHandler instance, got <class 'urllib.request.OpenerDirector'>
本帖最后由 suchocolate 于 2021-8-14 13:11 编辑
- import urllib.request
- # 方法1: 直接用创建的opener打开。
- url = "https://www.whatismyip.com"
- proxy_support = urllib.request.ProxyHandler({'http': '125.108.106.64:9000'})
- opener = urllib.request.build_opener(proxy_support)
- opener.addheaders = [('User-agent', 'Firefox')]
- response = opener.open(url)
- html = response.read().decode('utf-8')
- print(html)
- # 方法2:让创建的opener变成默认opener,然后用默认的urlopen方法打开。
- url = "https://www.whatismyip.com"
- proxy_support = urllib.request.ProxyHandler({'http': '125.108.106.64:9000'})
- opener = urllib.request.build_opener(proxy_support)
- opener.addheaders = [('User-agent', 'Firefox')]
- urllib.request.install_opener(opener)
- response = urllib.request.urlopen(url)
- html = response.read().decode('utf-8')
- print(html)
复制代码
|
|