【问题标题】:Using tor to make requests python?使用 tor 发出请求 python?
【发布时间】:2018-02-17 13:14:15
【问题描述】:

我是使用 requests 和 tor 的新手。

我正在使用的代码:

def get_tor_session():
    session = requests.session()
    # Tor uses the 9050 port as the default socks port
    session.proxies = {'http':  'socks5://127.0.0.1:9050',
                   'https': 'socks5://127.0.0.1:9050'}
    return session

session = get_tor_session()
print(session.get("http://httpbin.org/ip").text)

我不断收到以下错误:

引发 ConnectionError(e, request=request) requests.exceptions.ConnectionError: SOCKSHTTPConnectionPool(host='httpbin.org', port=80): Max retries exceeded with url: /ip (Caused by NewConnectionError(': 无法建立新连接: [WinError 10061] 无法连接是因为目标机器主动拒绝了它',))

我查看了各种答案,但无法确定问题所在。

【问题讨论】:

  • 确保 Tor 正在本地主机上运行,​​如果仍然无法连接,请尝试 9150
  • @t.m.adam 我尝试更改端口。仍然收到错误(在下面对 jamescampbell 的回答的评论中给出了错误)。 Tor 肯定在运行,因为 chromedriver 正在使用它来获取 webscrape。
  • 你不能用torify运行你的Python脚本吗?

标签: python-3.x python-requests tor


【解决方案1】:

下面是适合我的代码:

import requests
torport = 9050
proxies = {
    'http': "socks5h://localhost:{}".format(torport),
    'https': "socks5h://localhost:{}".format(torport)
}

print(requests.get('http://icanhazip.com', proxies=proxies).content)

检查以确保 Tor 正在您的计算机上运行,​​并且 Windows / Defender 等上的防火墙没有阻止您尝试访问的端口。

【讨论】:

  • 您好,感谢您的回复。 Tor正在运行,我正在将chromedriver与另一个带有tor的程序一起使用,它工作正常,所以我假设端口没有被阻塞。现在,当我运行上面的代码时,出现以下错误:>“无法从 %s 确定 SOCKS 版本”% proxy_url”无法弄清楚我在这里做错了什么。
  • 您确定安装了 pysocks 吗?我会通过sudo pip3 install requests[socks] 来确保您安装的版本可以通过请求正确修补猴子。
  • @Sid 很高兴听到。
【解决方案2】:

我遇到了同样的问题,下面的解决方案解决了它。

SOCKSHTTPConnectionPool(host='httpbin.org', port=80)

根据这一行,你电脑的监听端口配置了80端口,需要改成你在torrc文件中配置的SOCKSPort,我的SOCKSPort=9050,默认情况下,CONTROL PORT值设置为9051。 How to configure a tor proxy on windows? 这个链接解释了如何配置 tor。 确保 Tor 浏览器在后台运行。 希望这些信息对您有所帮助。

【讨论】:

    【解决方案3】:

    您可以像这样更改代码:

    def __init__(self):
        self.header = {'Content-Type': 'application/x-www-form-urlencoded'}
    
    # ***** proxy *****#
    def renew_connection(self):
        with db.Controller.from_port(port=9051) as controller:
            controller.authenticate(password='my_password')
            controller.signal(Signal.NEWNYM)
            controller.close()
    
    def request_tor(self, url, headers, post_fields):
        self.renew_connection()
        session = requests.session()
        session.proxies = {}
        session.proxies['http'] = 'socks5h://localhost:9050'
        r = session.post(url, headers=headers, data=post_fields)
    

    【讨论】:

      猜你喜欢
      • 2015-07-28
      • 2022-11-26
      • 1970-01-01
      • 1970-01-01
      • 2012-06-13
      • 2016-01-13
      • 2020-04-20
      • 1970-01-01
      相关资源
      最近更新 更多