Python:Pyppeteer with Asyncio [英] Python: Pyppeteer with asyncio

查看:26
本文介绍了Python:Pyppeteer with Asyncio的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一些测试,我想知道下面的脚本是否异步运行?

# python test.py  It took 1.3439464569091797 seconds.

31(站点)x 1.34=41.54s-因此少了几秒钟,但理论上应该只需要最长请求的时间?

# python test.py  It took 28.129364728927612 seconds.

可能在这里打开浏览器不是异步的,为此我应该使用executor

# cat test.py 
import asyncio
import time

from pyppeteer import launch
from urllib.parse import urlparse

WEBSITE_LIST = [
    'http://envato.com',
    'http://amazon.co.uk',
    'http://amazon.com',
    'http://facebook.com',
    'http://google.com',
    'http://google.fr',
    'http://google.es',
    'http://google.co.uk',
    'http://internet.org',
    'http://gmail.com',
    'http://stackoverflow.com',
    'http://github.com',
    'http://heroku.com',
    'http://djangoproject.com',
    'http://rubyonrails.org',
    'http://basecamp.com',
    'http://trello.com',
    'http://yiiframework.com',
    'http://shopify.com',
    'http://airbnb.com',
    'http://instagram.com',
    'http://snapchat.com',
    'http://youtube.com',
    'http://baidu.com',
    'http://yahoo.com',
    'http://live.com',
    'http://linkedin.com',
    'http://yandex.ru',
    'http://netflix.com',
    'http://wordpress.com',
    'http://bing.com',
]

start = time.time()

async def fetch(url):
    browser = await launch(headless=True, args=['--no-sandbox'])
    page = await browser.newPage()
    await page.goto(f'{url}', {'waitUntil': 'load'})
    await page.screenshot({'path': f'img/{urlparse(url)[1]}.png'})
    await browser.close()

async def run():
    tasks = []

    for url in WEBSITE_LIST:
        task = asyncio.ensure_future(fetch(url))
        tasks.append(task)

    responses = await asyncio.gather(*tasks)
    #print(responses)

#asyncio.get_event_loop().run_until_complete(fetch('http://yahoo.com'))
loop = asyncio.get_event_loop()
future = asyncio.ensure_future(run())
loop.run_until_complete(future)

print(f'It took {time.time()-start} seconds.')

推荐答案

根据pyppeteer源代码,使用subprocess不带管道的subprocess管理铬进程,websockets通信,因此是异步的。

您有31个站点,那么您将有31+1个进程。因此,除非您的CPU有32个内核(也可能有线程、系统进程、锁、超线程和所有影响结果的不同因素,所以这只是一个不精确的示例),否则它不会完全并行执行。因此,我认为瓶颈是CPU打开浏览器、渲染网页和转储为图像。使用Executor无济于事。

但是,它仍然是异步的。这意味着,您的Python进程没有被阻塞,您仍然可以同时运行其他代码或等待网络结果。只是当CPU被其他进程满载时,Python进程更难"窃取"CPU时间。

这篇关于Python:Pyppeteer with Asyncio的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆