Python:将proxybroker库与asyncio一起使用的正确方法
我想在python程序中使用lib生成一个包含10个工作代理的列表/队列 不幸的是,我无法在lib中找到任何类似的内容 这就是我现在得到的,但感觉我使用asyncio完成任务的方式不对。特别是我与Python:将proxybroker库与asyncio一起使用的正确方法,python,python-3.x,asynchronous,proxy,python-asyncio,Python,Python 3.x,Asynchronous,Proxy,Python Asyncio,我想在python程序中使用lib生成一个包含10个工作代理的列表/队列 不幸的是,我无法在lib中找到任何类似的内容 这就是我现在得到的,但感觉我使用asyncio完成任务的方式不对。特别是我与collect(proxies)调用结合使用的collect函数 def get_代理(self,limit=10): 异步def收集(代理): p=[] 尽管如此: proxy=等待代理。get() 如果代理为无: 打破 p、 附加(代理) 返回p 代理=asyncio.Queue() 经纪人=经纪人
collect(proxies)
调用结合使用的collect
函数
def get_代理(self,limit=10):
异步def收集(代理):
p=[]
尽管如此:
proxy=等待代理。get()
如果代理为无:
打破
p、 附加(代理)
返回p
代理=asyncio.Queue()
经纪人=经纪人(代理人)
tasks=asyncio.gather(
find(类型=['HTTP','HTTPS'],限制=10),
收集(代理)
loop=asyncio.get\u event\u loop()
代理列表=循环。运行直到完成(任务)
loop.close()
返回代理列表
生成代理列表的首选/正确方法是什么 您可以这样做:
"""Find and show 10 working HTTP(S) proxies."""
import asyncio
from proxybroker import Broker
async def show(proxies):
while True:
proxy = await proxies.get()
if proxy is None: break
print('Found proxy: %s' % proxy)
proxies = asyncio.Queue()
broker = Broker(proxies)
tasks = asyncio.gather(
broker.find(types=['HTTP', 'HTTPS'], limit=10),
show(proxies))
loop = asyncio.get_event_loop()
loop.run_until_complete(tasks)
或者,如果要生成文件:
import asyncio
from proxybroker import Broker
async def save(proxies, filename):
"""Save proxies to a file."""
with open(filename, 'w') as f:
while True:
proxy = await proxies.get()
if proxy is None:
break
proto = 'https' if 'HTTPS' in proxy.types else 'http'
row = '%s://%s:%d\n' % (proto, proxy.host, proxy.port)
f.write(row)
def main():
proxies = asyncio.Queue()
broker = Broker(proxies)
tasks = asyncio.gather(broker.find(types=['HTTP', 'HTTPS'], limit=10),
save(proxies, filename='proxies.txt'))
loop = asyncio.get_event_loop()
loop.run_until_complete(tasks)
if __name__ == '__main__':
main()
就这些
好看