playwright基本使用

本文介绍了如何在Python中使用Playwright库进行浏览器自动化测试,特别是使用火狐浏览器的无头模式进行模拟登录操作。通过XPath定位元素,执行点击、填写表单等动作,并获取localStorage的数据。
摘要由CSDN通过智能技术生成

python启动浏览器测试工具playwright
可用系统:
windows,ubuntu

1.安装
首先安装nodejs环境并添加如环境变量
官网:https://nodejs.org
验证nodejs是否安装成功

node -v
npm -v

安装playwright

pip3 install playwright
npm install playwright

安装playrright浏览器

playwright install chromium  # 谷歌浏览器
playwright install firefox  # 火狐浏览器
playwright install webkit  # webkit浏览器

2.示例:使用火狐浏览器无头模式启动模拟登录(协程版)

import asyncio
import json
from playwright.async_api import async_playwright
import random

async def run(playwright):
	# chromium = playwright.chromium 
	chromium = playwright.firefox  # or "firefox" or "webkit".
    browser = await chromium.launch_persistent_context(
        user_data_dir=r"火狐浏览器缓存位置",  # 浏览器缓存
        # user_data_dir=r"/root/.mozilla/firefox",  # 火狐浏览器缓存
        # args=["--no-sandbox", "--disable-setuid-sandbox"],
        args=['--disable-blink-features=AutomationControlled'],  # 禁用正在自动化控制提示
        headless=True
    )
    page = await browser.new_page()
    await page.goto("网站地址")
    await page.wait_for_timeout(2000)
    await page.mouse.move(random.uniform(100, 500), random.uniform(100, 500))
	# /html/head/title
    # 获取网页标题
    login_text = await page.title()
    awaitpage.click('xpath定位')  # 模拟点击
    await page.wait_for_timeout(1000)
    await page.fill('xpath', "输入文本")
    await page.wait_for_timeout(1000)
    await page.wait_for_load_state('networkidle')
    await page.wait_for_timeout(4000)
    await page.mouse.move(random.uniform(100, 500), random.uniform(100, 500))
    user_token = await page.evaluate('() => localStorage.getItem("缓存位置")')
    await page.wait_for_timeout(2000)
    await browser.close()
    print("user_token: ", user_token)

async def main():
    async with async_playwright() as playwright:
        return await run(playwright)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值