實用爬蟲-02-爬蟲真正使用代理 ip
# coding:utf-8
# 爬蟲使用代理IP
from urllib import request,error
if __name__ == '__main__':
# 0.設定測 ip 的地址
url = "http://2018.ip138.com/ic.asp"
# 1.設定代理 ip,獲取方法參照:https://www.cnblogs.com/xpwi/p/9600727.html
proxy = {'http':'189.201.142.129:57815'}
# 2.建立ProxyHandler
proxy_handler = request.ProxyHandler(proxy)
# 3.建立Opener
opener = request.build_opener(proxy_handler)
# 4.安裝Opener
request.install_opener(opener)
# 下面再進行訪問url就會使用代理伺服器
try:
rsp = request.urlopen(url)
html = rsp.read().decode('GBK')
print(html)
except error.HTTPError as e:
print(e)
except Exception as e:
print(e)
執行結果