python - 使用 TOR 运行 python 脚本

标签 python linux proxy tor

大家好!起初我想确保有类似的主题,但没有公认的答案或明确的回应。所以我想把它们结合起来再问。我有以下脚本:

import urllib2

proxy = urllib2.ProxyHandler({"http":"127.0.0.1:9050"})
opener = urllib2.build_opener(proxy)
print(opener.open("http://www.ifconfig.me/ip").read())

我想匿名运行它,例如使用 tor。但它给出了这个错误:

Traceback (most recent call last):
  File "python_tor.py", line 5, in <module>
    print(opener.open("http://www.ifconfig.me/ip").read())
  File "/usr/lib/python2.7/urllib2.py", line 400, in open
    response = meth(req, response)
  File "/usr/lib/python2.7/urllib2.py", line 513, in http_response
    'http', request, response, code, msg, hdrs)
  File "/usr/lib/python2.7/urllib2.py", line 438, in error
    return self._call_chain(*args)
  File "/usr/lib/python2.7/urllib2.py", line 372, in _call_chain
    result = func(*args)
  File "/usr/lib/python2.7/urllib2.py", line 521, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 501: Tor is not an HTTP Proxy

我在 stackoverflow 中找到了以下答案:

 proxy_support = urllib2.ProxyHandler({"http" : "127.0.0.1:8118"})
    opener = urllib2.build_opener(proxy_support) 
    opener.addheaders = [('User-agent', 'Mozilla/5.0')]
    print opener.open('http://www.google.com').read()

还有这个主题的评论:

It may be worthwhile for people reading this thread to know that port 8118 is actually Privoxy's port, not Tor. Tor is a strictly SOCKS-only proxy (port 9050) so it rejects all non-SOCKS traffic (e.g. HTTP). To handle non-SOCKS traffic, you would need to use Privoxy (port 8118) or Polipo (port 8123) to translate the traffic into SOCKS so Tor would accept.

Privoxy is better for privacy and Polipo is better for performance because it does caching.

谁能解释一下如何匿名执行我的脚本?

最佳答案

使用给定的答案是可能的:

import socks
import socket
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050)
socket.socket = socks.socksocket
import urllib2

print(urllib2.urlopen("http://www.ifconfig.me/ip").read())

但我很惊讶是否可以在每次新请求时更改 tor 的 ip 地址???

关于python - 使用 TOR 运行 python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9870182/

相关文章:

android - Gradle Sync问题:连接被拒绝:连接

.NET 3.5 升级到 .NET 4.0 后未调用 ASP.NET 通用处理程序

python - 使用 matplotlib 在另一个轴中嵌入多个插入轴

linux - 如何在 Linux 中加快编译时间

linux - 为具有开源 Linux 支持的 RFID 读取器开发软件 : Which direction to go, 硬件/系统方面?

linux - 如何使用bash中的变量内容传递给脚本中的查找?

django - 由于 CSRF 失败(Django 1.2.3)导致的间歇性 403s

python - 使用 Python MYSQL.Connector 插入 MySQL 表时出现错误

python - Django-compressor:如何写入 S3,从 CloudFront 读取?

Python 导入错误 : cannot import name XXXX