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)