# 作者:yancy
# 创建日期:2024/11/2 10:06
# 放屁: 钱 钱 钱
import asyncio
import time

from playwright.async_api import async_playwright
from playwright.sync_api import sync_playwright
import random
async def get_url(page, url):
    await page.goto(url, timeout=30*10000)

    await page.screenshot(path=f"{int(time.time()*1000000)}.png",full_page=True, timeout=10*10000)
    await page.wait_for_load_state("networkidle")
    print(await page.title())

    # await asyncio.sleep(random.randint(2,3))
    time.sleep(30)
    await page.close()
async def main():
    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=False)
        context = await browser.new_context()
        pages = [await context.new_page() for _ in urls]
        tasks = []
        for pg,url in zip(pages,urls):
            tasks.append(get_url(pg, url))

        await asyncio.gather(*tasks) 




def sync_main():
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=False)
        context = browser.new_context()
        pages = [context.new_page() for _ in urls]
        for pg,url in zip(pages,urls):
            pg.goto(url)
            # pg.
            time.sleep(2)
            print("当前页面的标题:", pg.title())
            pg.close()
if __name__ == "__main__":
    urls = [
        'https://playwright.dev/python/docs/api/class-page',
        'https://pythonziliao.com/post/542.html',
        'https://juejin.cn/post/7104964685576798239'

    ]
    asyncio.run(main()) # 异步版本
    # sync_main() # 同步版

同步和异步可以分开执行一遍。

posted on 2024-11-02 10:15  车仔面XO  阅读(12)  评论(1编辑  收藏  举报