如何将 SOCKS 4/5 代理与 urllib2 一起使用?

发布于 2024-08-22 19:17:11 字数 42 浏览 3 评论 0原文

如何使用带有 urllib2 的 SOCKS 4/5 代理来下载网页?

How can I use a SOCKS 4/5 proxy with urllib2 to download a web page?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

椒妓 2024-08-29 19:17:11

您可以使用 SocksiPy 模块。只需将文件“socks.py”复制到 Python 的 lib/site-packages 目录中,就可以开始了。

您必须在 urllib2 之前使用 socks。 (试试 pip install PySocks

例如:

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()

您还可以尝试 pycurl lib 和 tsocks,了解更多详细信息,请点击 这里

You can use SocksiPy module. Simply copy the file "socks.py" to your Python's lib/site-packages directory, and you're ready to go.

You must use socks before urllib2. (Try it pip install PySocks )

For example:

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()

You can also try pycurl lib and tsocks, for more detail, click on here.

晨光如昨 2024-08-29 19:17:11

当您需要同时使用许多不同的代理时,添加潘的答案的替代方案。

在这种情况下,您需要像使用 http 代理一样创建一个 opener。 GitHub 中有一个代码 https://gist.github.com/869791

opener = urllib2.build_opener(SocksiPyHandler(socks.PROXY_TYPE_SOCKS4, 'localhost', 9999))
print opener.open('http://www.whatismyip.com/automation/n09230945.asp').read()

Adding an alternative to pan's answer when you need to use many different proxies at the same time.

In that case you need to create an opener like you do with a http proxy. There is a code available in GitHub https://gist.github.com/869791

opener = urllib2.build_opener(SocksiPyHandler(socks.PROXY_TYPE_SOCKS4, 'localhost', 9999))
print opener.open('http://www.whatismyip.com/automation/n09230945.asp').read()
束缚m 2024-08-29 19:17:11

由于 SOCKS 是套接字级代理,因此您必须替换 urllib2 使用的套接字对象。请看一下这个解决方案。如果猴子修补对您来说不够好,那么您可以尝试子类化或复制修改 urllib2 标准库中的代码。

Since SOCKS is a socket level proxy, you have to replace the socket object used by urllib2. Please take a look a this solution. If monkey patching is not good enough for you, then you can try to subclass or copy-modify the code from the urllib2 standard library.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文