页面载入需要时间,因此需要进行多次定时的截图,所以需要用playwright实现异步截图
其实这个动作是不是必需的? 也许还是值得商量的
另外 await page.screenshot(path=output_path, full_page=True) full_page=True/False代表是否进行全屏截图
browser = await p.chromium.launch(headless=True)
headless=True/False 代表是否让浏览器展示(有头/无头)
import asyncio
from playwright.async_api import async_playwright
async def take_screenshot(url, output_path, delay=0):
async with async_playwright() as p:
# 启动无头浏览器
browser = await p.chromium.launch(headless=True)
context = await browser.new_context()
page = await context.new_page()
# 导航到目标页面
await page.goto(url)
# 等待页面加载完成
await page.wait_for_load_state("networkidle")
# 如果需要延迟截图,等待指定的时间
if delay > 0:
await asyncio.sleep(delay)
# 截取整个页面的截图
await page.screenshot(path=output_path, full_page=True)
# 关闭浏览器
await browser.close()
# 示例调用
async def main():
url = "https://example.com" # 替换为实际的页面 URL
output_path = "screenshot.png" # 保存截图的路径
delay = 5 # 延迟 5 秒后截图
# 启动异步截图任务
await take_screenshot(url, output_path, delay)
# 运行异步主函数
asyncio.run(main())