插件-playwright截图

提供palywright的页面句柄或者元素句柄即可截图,返回图片路径 。

import asyncio
import datetime
import logging
import os
import random

from playwright.async_api import async_playwright, ElementHandle, Page


async def screenshot_page(page: Page | ElementHandle,
                          folder_path: str | None = None,
                          file_name: str = datetime.datetime.now().strftime(
                              '%Y-%m-%d_%H-%M-%S-%f') + f'[{random.randint(0, 99999)}]') -> str:
    """
    :param page 页面句柄或者定位器
    :param folder_path 文件夹地址
    :param file_name 文件名称
    """
    screenshot_path = f'{file_name}_element.png'
    if isinstance(page, ElementHandle):
        if folder_path:
            screenshot_path = os.path.join(folder_path, f'{file_name}_element.png')
        await page.screenshot(path=screenshot_path)
    elif isinstance(page, Page):
        if folder_path:
            screenshot_path = os.path.join(folder_path, f'{file_name}_page.png')
        await page.screenshot(path=screenshot_path, full_page=True)
    else:
        if folder_path:
            screenshot_path = os.path.join(folder_path, f'{file_name}_element.png')
        await page.screenshot(path=screenshot_path)
    return screenshot_path


# 使用示例
async def main():
    async def start_chrome():
        command = r'"C:\Users\Lenovo\AppData\Local\Google\Chrome\Application\chrome.exe" --remote-debugging-port=9998 --user-data-dir=D:/chrome_user_data/15925828527 --window-position=10000,10000 --start-maximized'
        process = await asyncio.create_subprocess_shell(command)
        return process

    # 启动 Chrome
    chrome_process = await start_chrome()

    async with async_playwright() as p:
        browser = await p.chromium.connect_over_cdp(f"http://localhost:{9998}")
        content = browser.contexts[0]
        page = await content.new_page()
        await page.goto("https://www.baidu.com", timeout=60 * 1000)
        page_path = await screenshot_page(page=page, file_name=datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S-%f'))
        logging.info(f"Page screenshot saved to {page_path}")
        await asyncio.sleep(1)
        # 等待页面加载完成
        await page.wait_for_load_state('networkidle')
        # 选择要截图的元素(例如百度搜索框)
        element = await page.query_selector('input[name="wd"]')
        element_path = await screenshot_page(page=element,
                                             file_name=datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S-%f'))
        logging.info(f"Element screenshot saved to {element_path}")
        await page.close()
        await content.close()
        await browser.close()


if __name__ == '__main__':
    asyncio.run(main())

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

文子阳

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值