在 playwright.chromium.launch()
中传入 proxy
参数即可,示例代码如下:
from playwright.sync_api import sync_playwright
proxy = {'server': 'http:/127.0.0.1:8080'}
def run():
with sync_playwright() as p:
browser = p.chromium.launch(headless=False, proxy=proxy)
page = browser.new_page()
page.goto('https://www.baidu.com')
title = page.title()
if "百度" in title:
print("打开百度成功")
else:
print("打开百度失败")
browser.close()
run()
from playwright.async_api import async_playwright
import asyncio
proxy = {'server': 'http:/127.0.0.1:8080'}
async def run():
async with async_playwright() as p:
browser = await p.chromium.launch(headless=False, proxy=proxy)
page = await browser.new_page()
await page.goto('https://www.baidu.com')
title = await page.title()
if "百度" in title:
print("打开百度成功")
else:
print("打开百度失败")
await browser.close()
asyncio.get_event_loop().run_until_complete(run())
async/await
语法一般来说对于现代化系统,异步编程模型将是主流趋势。但同步在某些场景也同样易用。选择时要根据具体需求来权衡。
算是个入门的例子,关于每句话的意思,看我注释即可,示例代码如下:
import re
from playwright.sync_api import Page, expect, sync_playwright
proxy = {'server': 'http://127.0.0.1:8080'}
def test_baidu():
with sync_playwright() as p:
browser = p.chromium.launch(headless=False, proxy=proxy)
page = browser.new_page()
# 跳转到baidu页面
page.goto("https://www.baidu.com/")
# 点击输入框
page.locator("#kw").click()
# 输入框输入selenium
page.locator("#kw").fill("selenium")
# 点击百度一下查询按钮
page.get_by_role("button", name="百度一下").click()
# 验证输入框是否输入selenium
expect(page.locator("#kw")).to_have_value("selenium")
# 验证页面是否包含文本“大家还在搜”
expect(page.locator("#content_left")).to_contain_text("大家还在搜")
# 退出浏览器
browser.close()
注意:
测试类和测试方法都要用test_ 前缀命名
这是 Playwright 常用操作列表,请注意,还有许多其他操作,请务必查看定位器 API 部分以了解更多相关信息。
操作 | 描述 |
---|---|
locator.check() | 选中输入复选框 |
locator.click() | 点击元素 |
locator.uncheck() | 取消选中输入复选框 |
locator.hover() | 将鼠标悬停在元素上 |
locator.fill() | 填写表单字段,输入文本 |
locator.focus() | 聚焦元素 |
locator.press() | 按下单个键 |
locator.set_input_files() | 选择要上传的文件 |
locator.select_option() | 从下拉菜单中选择选项 |
断言 | 描述 |
---|---|
expect(locator).to_be_checked() | 复选框处于选中状态 |
expect(locator).to_be_enabled() | 控件已启用 |
expect(locator).to_be_visible() | 元素可见 |
expect(locator).to_contain_text() | 元素包含文本 |
expect(locator).to_have_attribute() | 元素具有属性 |
expect(locator).to_have_count() | 元素列表已给出长度 |
expect(locator).to_have_text() | 元素匹配文本 |
expect(locator).to_have_value() | 输入元素具有值 |
expect(page).to_have_title() | 页面有标题 |
expect(page).to_have_url() | 页面有 URL |
示例代码:
import pytest
from playwright.sync_api import Page, expect, sync_playwright
@pytest.fixture(scope="function", autouse=True)
def before_each_after_each(page: Page):
print("before the test runs")
page.goto("https://www.baidu.com/")
yield
print("after the test runs")
def test_main_navigation(page: Page):
page.locator("#kw").fill("久曲健 博客园")
page.get_by_role("button", name="百度一下").click()
expect(page.locator("#content_left")).to_contain_text("久曲健 - 博客园")
代码解释: