所以我有一些使用 praw API 的代码,我想通过代理运行它们。我在 this question 下找到了以下代码它对我有用。
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())
我的问题是它是否也会通过代理管道连接 praw 网络?我开始研究原始代码,试图了解它是如何工作的,但它对我来说太复杂了,我无法决定它是否会工作。 你们中有没有人有足够的经验来告诉我 praw 的网络是如何工作的,或者 soks 代理是如何工作的,或者可以告诉我如何找到答案?
非常感谢您对我的帮助。
最佳答案
这可以实现吗?
是的。 Python 使用 Requests 库发出 HTTP(S) 请求。根据this answer和 Requests documentation , requests>=2.10.0
通过 PySocks 支持 SOCKS 代理。
版本兼容性
截至此答案,prawcore
(praw
取决于)需要 requests >=2.6.0, <3.0
。您可能有 requests
的某个版本已安装至少 2.10.0
,但您可以检查以下内容:
$ python3 -c 'import requests; print(requests.__version__)'
如果您安装的版本低于2.10.0
,升级为:
$ python3 -m pip install 'requests >=2.10.0, <3.0'
代理配置
根据链接的答案,我们设置了 dict
我们的代理的(使用 'https'
代替 'http'
因为所有 PRAW 的请求都通过 HTTPS 发生):
proxies = {'https': 'socks5://127.0.0.1:9050'}
然后我们必须将其传递给 Session
PRAW 使用的。我们使用 proxies
argument 实例化它:
import requests
socks_session = requests.Session(proxies=proxies)
PRAW documentation mentions how to use a custom Session
:
The
requestor_class
andrequestor_kwargs
allow for customization of the requestorSession
in a caching layer.
这是我们如何传入自定义 Session
到 PRAW:
reddit = praw.Reddit(client_id='XX',
client_secret='XX',
user_agent='my_bot by pythoniac',
# ... more kwargs ...
requestor_kwargs={'session': socks_session})
PRAW 通过 Requests 发出的任何请求都将通过 SOCKS 代理。
DNS解析
注意什么Requests documentation关于 DNS 解析时的 SOCKS 代理的描述:
Using the scheme
socks5
causes the DNS resolution to happen on the client, rather than on the proxy server. This is in line with curl, which uses the scheme to decide whether to do the DNS resolution on the client or proxy. If you want to resolve the domains on the proxy server, usesocks5h
as the scheme.
关于python - PySocks代理功能可以与praw API一起使用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56558433/