反爬利器--設定代理伺服器
阿新 • • 發佈:2018-12-21
1 import urllib.request
2
3 # 構建兩個代理Handler,一個有代理IP,一個沒有
4 httpproxy_handler = urllib.request.ProxyHandler({"http": "211.141.111.114:61395"})
5 nullproxy_handler = urllib.request.ProxyHandler({})
6 proxy_switch = True # 定義一個代理開關
7
8 # 通過urllib.request.build_opener() 方法建立自定義opener物件
9 # 根據代理開關是否開啟,使用不同的代理模式
10 if proxy_switch:
11 opener = urllib.request.build_opener(httpproxy_handler)
12 else:
13 opener = urllib.request.build_opener(nullproxy_handler)
14
15 request = urllib.request.Request("http://www.baidu.com")
16 response = opener.open(request)
17 print(response.read())