【发布时间】:2015-04-21 23:17:42
【问题描述】:
我正在尝试使用 Python 编写的爬虫来爬取网站,并希望将 Tor 与 Python 集成,这意味着我想使用 Tor 匿名爬取网站。
我在 stackoverflow 上找到了一些答案,但没有一个对我有用。
这是我从Urllib2 using Tor and socks in python找到的第一个解决方案
import socks
import socket
import urllib2
socks.setdefaultproxy(socks.PROXY_TYPE_HTTP, "127.0.0.1", 9050)
socket.socket = socks.socksocket
print urllib2.urlopen('http://my-ip.herokuapp.com').read()
但我得到以下错误
(501, 'Tor is not an HTTP Proxy')
那么,How can I use a SOCKS 4/5 proxy with urllib2? 接受的答案
import socks
import socket
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 8080)
socket.socket = socks.socksocket
import urllib2
print urllib2.urlopen('http://www.google.com').read()
我得到以下错误
<urlopen error [Errno 111] Connection refused>
那么,来自Python urllib over TOR?的最高投票答案
import socks
import socket
def create_connection(address, timeout=None, source_address=None):
sock = socks.socksocket()
sock.connect(address)
return sock
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050)
# patch the socket module
socket.socket = socks.socksocket
socket.create_connection = create_connection
import urllib2
我的测试 url 是“http://almien.co.uk/m/tools/net/ip/”,上面的代码会运行 2 分钟,并以下面的错误结束
File "/usr/lib/python2.7/dist-packages/socks.py", line 369, in connect
self.__negotiatesocks5(destpair[0],destpair[1])
File "/usr/lib/python2.7/dist-packages/socks.py", line 236, in __negotiatesocks5
raise Socks5Error(ord(resp[1]),_generalerrors[ord(resp[1])])
IndexError: tuple index out of range
有人评论说最新的端口是9150但是9050,所以我再次尝试使用9150,并得到以下错误
urllib2.URLError: <urlopen error [Errno 111] Connection refused>
更新
在我的机器上添加 Tor 信息。
root@xxxxxxx:~# tor
Apr 22 14:14:39.818 [notice] Tor v0.2.4.20 (git-0d50b03673670de6) running on Linux with Libevent 2.0.21-stable and OpenSSL 1.0.1f.
Apr 22 14:14:39.818 [notice] Tor can't help you if you use it wrong! Learn how to be safe at https://www.torproject.org/download/download#warning
Apr 22 14:14:39.818 [notice] Read configuration file "/etc/tor/torrc".
Apr 22 14:14:39.820 [notice] Opening Socks listener on 127.0.0.1:9050
Apr 22 14:14:39.000 [notice] Parsing GEOIP IPv4 file /usr/share/tor/geoip.
Apr 22 14:14:39.000 [notice] Parsing GEOIP IPv6 file /usr/share/tor/geoip6.
Apr 22 14:14:39.000 [warn] You are running Tor as root. You don't need to, and you probably shouldn't.
Apr 22 14:14:39.000 [warn] OpenSSL version from headers does not match the version we're running with. If you get weird crashes, that might be why. (Compiled with 1000105f: OpenSSL 1.0.1e 11 Feb 2013; running with 1000106f: OpenSSL 1.0.1f 6 Jan 2014).
Apr 22 14:14:40.000 [notice] Bootstrapped 5%: Connecting to directory server.
【问题讨论】:
-
您的系统上是否运行了 Tor?
-
啊...如何检查/打开它?我的操作系统是 ubuntu。