self_example/Spider/Chapter07_动态渲染页面爬取/playwrightLearning/demo2代码生成.py

34 lines
1.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#-*- encoding:utf-8 -*-
'''
@Author : dingjiawen
@Date : 2023/12/7 14:00
@Usage :
@Desc :playWright有一个强大的功能是可以录制我们在浏览器中的操作并自动生成代码
'''
from playwright.sync_api import Playwright, sync_playwright, expect
def run(playwright: Playwright) -> None:
browser = playwright.firefox.launch(headless=False)
# 这里使用context而不是browser可以让每个context都是一个独立的上下文环境资源隔离
context = browser.new_context()
page = context.new_page()
page.goto("https://www.baidu.com/")
page.locator("#kw").click()
page.locator("#kw").fill("python")
page.get_by_role("button", name="百度一下").click()
page.get_by_role("button", name="百度一下").click()
page.locator("#kw").click()
page.locator("#kw").fill("nba")
page.get_by_role("button", name="百度一下").click()
page.close()
# ---------------------
context.close()
browser.close()
with sync_playwright() as playwright:
run(playwright)