python - PySocks代理功能可以与praw API一起使用吗?

标签 python networking reddit socks praw

所以我有一些使用 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 answerRequests 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 and requestor_kwargs allow for customization of the requestor Reddit will use. This allows, e.g., easily adding behavior to the requestor or wrapping its Session 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, use socks5h as the scheme.

关于python - PySocks代理功能可以与praw API一起使用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56558433/

相关文章:

c++ - Arduino 在 Linux 上的多个 http 请求期间挂起,但在 Windows 上不挂起

networking - 使用代理从以太网创建无需代理身份验证的热点

jquery - 来自带有 CORS 的 jQuery ajax 的 Reddit API : No 'Access-Control-Allow-Origin' header is present on the requested resource

css - 无法让 Z-index 将::after background 放在同一个 div 的背景下。这可能吗?

javascript - 如何修复此循环,以便在单击时加载并打开正确的链接?

python - 为什么 Flask 应用程序运行但浏览器未加载页面?

python - 使用字典中的值过滤 Pandas 数据框

Python-将元组值添加到字典中的重复键

python - 由于回复 pidboxes,Redis 在用作 Celery 代理时会占用大量内存

networking - 配置运行 docker 容器的主机的网络接口(interface)