爬虫(ProxyHandler)——代理

工具:python3

步骤:

1)使用ProxyHandler()构建httpproxy_handler对象 

2)使用build_opener(httpproxy_handler)构建opener

3)使用Request()构造请求

4)使用install_opener()构造一个全局opener

5)发送请求

import urllib.request

# 代理开关,表示是否启用代理
proxyswitch = True

# 构建一个Handler处理器对象,参数是一个字典,包括代理类型和代理服务器IP,port
httpproxy_handler = urllib.request.ProxyHandler({"http": "175.42.122.115:808"})

# 构建一个没有代理的处理器对象,也要有一个空字典返回
nullproxy_handler = urllib.request.ProxyHandler({})

if proxyswitch:
    opener = urllib.request.build_opener(httpproxy_handler)
else:
    opener = urllib.request.build_opener(nullproxy_handler)

request = urllib.request.Request("http://www.baidu.com/")

# 构建一个全局opener,之后所有的请求都可以用urlopen()方式发出去,也附带handler功能 urllib.request.install_opener(opener) request
= urllib.request.urlopen(request) print(request.read())
原文地址:https://www.cnblogs.com/gaoquanquan/p/9108012.html