当前位置: 代码网 > it编程>前端脚本>Python > Playwright设置base_url的三种方式

Playwright设置base_url的三种方式

2026年01月25日 Python 我要评论
方式一:playwright创建new_context()在new_context(base_url=‘’)中指定base_url browser = playwrigh

方式一:playwright创建new_context()

  • 在new_context(base_url=‘’)中指定base_url
    browser = playwright.chromium.launch(headless=false)
    context = browser.new_context(base_url="http://localhost:8080")

示例代码:

import json

from playwright.sync_api import playwright, sync_playwright


def run(playwright: playwright) -> none:
    browser = playwright.chromium.launch(headless=false)
    context = browser.new_context(base_url="http://localhost:8080")
    page = context.new_page()
    page.goto("/login")
    page.get_by_role("textbox", name="用户名").click()
    page.get_by_role("textbox", name="用户名").fill("admin")
    page.get_by_role("textbox", name="密码").click()
    page.get_by_role("textbox", name="密码").fill("admin123")
    page.get_by_role("button", name="登录").click()
    # 等待页面跳转,作为登录成功的标准
    page.wait_for_url(url='http://localhost:8080/index')
    # page.pause()

    # 保存storage state 到指定的文件
    # 使用该方法前,需要确认网站cookie的失效时间
    storage = context.storage_state(path='../../auth/ry_auto.json')
    print(storage)
    # ---------------------
    context.close()
    browser.close()


with sync_playwright() as playwright:
    run(playwright)

方式二:使用插件pytest-playwright

pip install pytest-playwright
  • pytest.ini配置文件中,使用addopts属性在命令行中添加参数--base-url http://localhost:8080

pytest.ini配置文件如下:

[pytest]
addopts = -s --base-url http://localhost:8080

方式三:使用插件pytest-base-url

  • 该插件在pytest.ini配置文件中,添加了一个行属性,base_url
pip install pytest-base-url

pytest.ini配置文件如下:

[pytest]
base_url = http://localhost:8080

到此这篇关于playwright设置base_url的三种方式的文章就介绍到这了,更多相关playwright设置base_url内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com