Playwright asynchronous implementation opens a link in the current tab

To use the asynchronous API in Playwright and open a link in the current tab, follow the steps below. First make sure that the Playwright library is installed, if not, install it with the following command:

pip install playwright
playwright install

Next, create a Python script and import the required modules, the following is an example of opening a link in the current tab using the Playwright asynchronous API:

import asyncio
from playwright.async_api import async_playwright

async def main():
    async with async_playwright() as p:
        browser = await p.chromium.launch()
        context = await browser.new_context()

        # 打开一个新页面并导航到目标网址
        page = await context.new_page()
        await page.goto("https://example.com")

        # 点击页面中的a链接
        await page.click('a')

        # 等待页面导航完成
        await page.wait_for_load_state("networkidle")

        # 处理当前页面
        print("当前页面的标题:", await page.title())

        # 关闭浏览器
        await browser.close()

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

In this example, we use async_playwright()a context manager to create a Chromium browser instance. Then, we create a new browser context and open a new page in it. Next, we navigate to the destination URL (https://example.com in this example).

In order to open a link in the current tab, we use await page.click('a')the command, which will click on the first <a>element on the page. We then wait for the page navigation to complete, print the title of the current page and close the browser.

Guess you like

Origin blog.csdn.net/lilongsy/article/details/130016261