做爬虫时常遇到需要切换代理的情况,mitmproxy 对python有很好的支持,可以通过python脚本自定义二级代理的代理方式。
第一步 命令行启用upstream模式
注: 只有在一开始启动了upstream 模式, 后续才可以进行定制化跳转
mitmdump --mode upstream:http://defaule-upstream-proxy.local:8080/ -s ./change_upstream_proxy.py
第二步 mitmdump 脚本根据所需定义规则,跳转不同的二级代理
def request(flow:http.HTTPFlow) -> None:
if flow.request.method == "CONNECT":
# if the decision is done by domain, one could alse modify the server address here.
# We do it after CONNECT here to have the reqeust data available as well.
return
client_ip = flow.client_conn.address[0]
if 'xxx.com' in flow.request.url:
ctx.log.info(flow.request.url)
proxy = ("localhost", 8888)
else:
proxy = ("localhost", 3800)
#这里配置二级代理的IP地址和端口
if flow.live:
flow.live.change_upstream_prxoy_server(proxy)
第三部 测试
可以通过访问 http://httpbin.org/get 或者http://httpbin.org/ip 来测试自己的代理ip是否成功。