wangshaoqing 321bbff1c1 添加学习教程目录(learning/)及对应单元测试
- 新增 DrissionPage 基础教程(01-05)
- 新增 Playwright 基础教程(01-05)
- 新增网络基础教程(01-05)
- 新增 test_learning_examples.py 单元测试
- 更新 .gitignore 忽略 learning/*/output/ 目录
2026-05-06 16:39:55 +08:00

44 lines
1.2 KiB
Python
Raw Permalink 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.

"""
练习 03: 用 Playwright 等待元素并定位元素。
目标:
1. 练会 `page.locator(...)`
2. 练会 `page.get_by_role(...)`
3. 练会等待元素出现
4. 成功打印一个稳定元素的文本内容
建议:
- 先选一个结构稳定的页面,不要一上来就拿复杂站点练
- 如果定位不到元素,先打印页面标题和 URL确认你打开的是对的页面
- 第一版优先使用 role / text 这种更直观的定位方式
运行:
./.venv/bin/python learning/playwright_basics/03_wait_and_locate.py
"""
DEFAULT_URL = "https://example.com/"
def main() -> None:
from playwright.sync_api import sync_playwright
with sync_playwright() as playwright:
browser = playwright.chromium.launch(headless=False)
page = browser.new_page()
page.goto(DEFAULT_URL)
heading = page.get_by_role("heading", name="Example Domain")
heading.wait_for()
print(f"[INFO] 标题文本: {heading.text_content()}")
first_paragraph = page.locator("p").first
first_paragraph.wait_for()
print(f"[INFO] 第一段文本: {first_paragraph.text_content()}")
input("按回车退出...")
browser.close()
if __name__ == "__main__":
main()