Python的mechanize代理支持

9 投票
2 回答
20031 浏览
提问于 2025-04-15 17:36

我有一个关于Python的mechanize库支持代理的问题。我正在写一个网页客户端的脚本,想在我的脚本里加入代理支持的功能。

比如说,如果我有:

params = urllib.urlencode({'id':id, 'passwd':pw})
rq = mechanize.Request('http://www.example.com', params) 
rs = mechanize.urlopen(rq)

我该如何在我的mechanize脚本中添加代理支持呢?每次我打开这个 www.example.com 网站时,我希望它都能通过代理来访问。

2 个回答

32

我不太确定这是否有帮助,但你可以在mechanize这个代理浏览器上设置代理选项。

br = Browser()
# Explicitly configure proxies (Browser will attempt to set good defaults).
# Note the userinfo ("joe:password@") and port number (":3128") are optional.
br.set_proxies({"http": "joe:password@myproxy.example.com:3128",
                "ftp": "proxy.example.com",
                })
# Add HTTP Basic/Digest auth username and password for HTTP proxy access.
# (equivalent to using "joe:password@..." form above)
br.add_proxy_password("joe", "password")
9

你可以使用 mechanize.Request.set_proxy(host, type) 这个方法(至少在版本 0.1.11 及之后的版本中可以用)。

假设你有一个 HTTP 代理在本地的 8888 端口上运行。

req = mechanize.Request("http://www.google.com")
req.set_proxy("localhost:8888","http")
mechanize.urlopen(req)

这样应该可以正常工作。

撰写回答