前言
我们在进行 web 自动化时,经常遇到一些不好操作的元素,普通的元素定位和操作容易报错,如果我们使用的 selenium 的话,就可以使用 selenium 调用 js 脚本进行操作。在 playwright 中也有类似的方法,使用 page.evaluate()执行 JavaScript 脚本。page.evaluate()和 page.evaluate_handle()之间的唯一区别是 page.evaluate_handle()返回 JSHandle。
page.evaluate()
返回 evaluate() 返回执行 JavaScript 脚本的结果,使用示例如下:
from playwright.sync_api import sync_playwright
def run_js_script():
with sync_playwright() as playwright:
browser = playwright.chromium.launch(headless=False)
context = browser.new_context()
page = context.new_page()
page.goto('https://www.baidu.com')
print(page.evaluate("1 + 2"))
# 关闭浏览器
context.close()
browser.close()
run_js_script()
复制代码
也可以执行一个函数,如下:
from playwright.sync_api import sync_playwright
def run_js_script():
with sync_playwright() as playwright:
browser = playwright.chromium.launch(headless=False)
context = browser.new_context()
page = context.new_page()
page.goto('https://www.baidu.com')
print(page.evaluate("() => '拜仁慕尼黑'"))
# 关闭浏览器
context.close()
browser.close()
run_js_script()
复制代码
注:如果传递给 page.evaluate()的函数返回一个不可序列化的值,则 page.evaluate()解析为 undefined
示例
打印网页标题
执行 document.title 获取页面的 title,代码如下:
from playwright.sync_api import sync_playwright
def run_js_script():
with sync_playwright() as playwright:
browser = playwright.chromium.launch(headless=False)
context = browser.new_context()
page = context.new_page()
page.goto("https://www.baidu.com/")
title = page.evaluate('document.title')
print(title)
page.pause()
# 关闭浏览器
context.close()
browser.close()
run_js_script()
复制代码
操作元素示例
from playwright.sync_api import sync_playwright
def run_js_script():
with sync_playwright() as playwright:
browser = playwright.chromium.launch(headless=False)
context = browser.new_context()
page = context.new_page()
page.goto("https://www.baidu.com/")
js = """
document.getElementById('kw').value='playwright';
document.getElementById('su').click();
"""
page.evaluate(js)
page.pause()
# 关闭浏览器
context.close()
browser.close()
run_js_script()
复制代码
页面如下:
page.evaluate_handle()
page.evaluate_handle()的返回值是 JSHandle。
from playwright.sync_api import sync_playwright
def run_js_script():
with sync_playwright() as playwright:
browser = playwright.chromium.launch(headless=False)
context = browser.new_context()
page = context.new_page()
page.goto("https://www.baidu.com/")
a_handle = page.evaluate_handle("document.body")
result_handle = page.evaluate_handle("body => body.innerHTML", a_handle)
print(result_handle.json_value())
result_handle.dispose()
page.pause()
# 关闭浏览器
context.close()
browser.close()
run_js_script()
复制代码
总结
本文主要介绍了 playwright 执行 js 脚本的操作,与 selenium 一样,playwright 同样可以执行 js 脚本来完成一些不便操作的元素。
评论