【问题标题】:Python mechanize - set_proxies method ignores proxy and does nothingPython mechanize - set_proxies 方法忽略代理并且什么都不做
【发布时间】:2016-05-04 12:04:46
【问题描述】:

我在创建 mechanize broswer 实例时尝试设置 http 代理,但它似乎根本不起作用或引发任何类型的错误。

from mechanize import Browser
br = Browser()
ua = 'Mozilla/5.0 (X11; Linux x86_64; rv:18.0) Gecko/20100101 Firefox/1    8.0 (compatible;)'
br.addheaders = [('User-Agent', ua), ('Accept', '*/*')]
br.set_proxies({'http':'116.226.11.254:8118'})
br.open("https://xxx.xxx")

此代码仍然使用本地 ip 打开 url,根本不使用代理。如果代理无法访问,那么它应该抛出这样的错误,但它没有发生。我试图为代理输入一些无效的 ip,例如

br.set_proxies({'http':'116.22as6.11.25as4:8118'})

但是这段代码也没有抛出任何错误!! 是否有可能其他一些内置 python 代码正在重写代理? 我在具有最新机械化的虚拟环境中使用 python 2.7.10,并尝试使用此代码打开 https 地址

我试过this,但它仍然忽略代理

【问题讨论】:

    标签: python proxy mechanize


    【解决方案1】:

    请注意,您只是为“http”协议设置代理,但在 br.open 中调用“https”。

    尝试将 br.set_proxies 中的协议替换为“https”。

    【讨论】:

    • http 用于设置代理中的代理类型。我使用的代理是 Http 而不是 https。
    【解决方案2】:

    经过几个小时的研究,我意识到机械化的这个功能是无用的,所以我找到了另一种方法来处理机械化请求:

    #!/usr/bin/python
    import mechanize
    import socks
    import socket
    
    # This will be printing your real ip
    print mechanize.Browser().open("https://api.ipify.org/?format=raw").read()
    ip = "0.0.0.0"
    port = 1234
    socks.setdefaultproxy(socks.PROXY_TYPE_HTTP, ip, port)
    socket.socket = socks.socksocket
    
    br = mechanize.Browser()
    br.set_handle_equiv(True)
    br.set_handle_redirect(True)
    br.set_handle_referer(True)
    br.set_handle_robots(False)
    br.addheaders = [("User-agent", "Mozilla/5.0")]
    # Then with your proxy:
    print br.open("https://api.ipify.org/?format=raw").read()
    # Will be printing the ip from the proxy
    

    然后这真的对我有用。我希望这对你有用!

    【讨论】:

    • 如果您需要帮助,请更好地描述您的代码为何会有所帮助。因为您在 Accept 标头中只有一个差异。
    【解决方案3】:
    br.set_handled_schemes(['https', 'http'])
    

    为我做的。

    【讨论】:

      猜你喜欢
      • 2012-04-02
      • 2015-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多