python - 通过 Tor 进行多线程 Python 请求

标签 python proxy python-requests tor

以下代码是我尝试通过 tor 执行 python 请求,效果很好,但我有兴趣为此添加多线程。

所以我想同时执行大约 10 个不同的请求并处理它们的输出。最简单、最有效的方法是什么?

def onionrequest(url, onionid):
    onionid = onionid
    session = requests.session()
    session.proxies = {}
    session.proxies['http'] = 'socks5h://localhost:9050'
    session.proxies['https'] = 'socks5h://localhost:9050'
    #r = session.get('http://google.com')


    onionurlforrequest = "http://" + url

    try:
        r = session.get(onionurlforrequest, timeout=15)
    except:
        return None
    if r.status_code = 200:
        listofallonions.append(url)

最佳答案

我建议使用以下软件包来实现此目的:asyncioaiohttpaiohttp_socks

示例代码:

import asyncio
import aiohttp
from aiohttp_socks import ProxyConnector

async def fetch(session, url):
    async with session.get(url) as response:
        return await response.text()

async def main(urls):
    tasks = []
    connector = ProxyConnector.from_url('socks5://localhost:9150', rdns=True)
    async with aiohttp.ClientSession(connector=connector, rdns=True) as session:
        for url in urls:
            tasks.append(fetch(session, url))
        htmls = await asyncio.gather(*tasks)
        for html in htmls:
            print(html)

if __name__ == '__main__':
    urls = [
            'http://python.org',
            'https://google.com',
            ...
        ]
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main(urls))

一开始使用 asyncio 可能会有点令人畏惧,因此您可能需要练习一段时间才能掌握它的窍门。

如果您想更深入地了解同步和异步之间的区别,请查看 this问题。

关于python - 通过 Tor 进行多线程 Python 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55882199/

相关文章:

python - 对 namedtuple 类进行自定义排序

python - Pandas /pyplot 散点图 : set axis labels not working

spring - Tomcat 无法读取架构文档

python - beautifulsoup select 方法返回回溯

python - 如何使用 requests.get() 仅获取 <body> 标记内的文本?

python - 如何从实例内部获取 Zope 安装的位置?

python - 在 png 上绘制 matplotlib 散点图

angular - Angular App 中 proxy.conf.json 的 CORS 问题

.Net web请求通过代理,自动检测凭据

python - 请求/aiohttp : closing response objects