Puppeteer:如何在评估函数中使用 XPath 和外部变量? [英] Puppeteer: How to use XPath and external Variable in evaluate function?

查看:53
本文介绍了Puppeteer:如何在评估函数中使用 XPath 和外部变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Puppeteer 的评估函数中使用 XPath 和外部变量,但是有一个问题:

I am trying to use an XPath and an external variable in Puppeteer's evaluate function, but there is a problem:

  • 如果我使用评估函数并传入外部变量,则无法传入 XPath,
  • 如果我删除 XPath 一切正常,但我需要使用 XPath 来完成.

我刚刚收到此错误:

UnhandledPromiseRejectionWarning: TypeError: 转换循环JSON 的结构-->从构造函数BrowserContext"的对象开始|属性 '_browser' ->带有构造函数浏览器"的对象--- 属性 '_defaultContext' 关闭圆圈 您是否正在传递嵌套的 JSHandle?在 JSON.stringify()

UnhandledPromiseRejectionWarning: TypeError: Converting circular structure to JSON --> starting at object with constructor 'BrowserContext' | property '_browser' -> object with constructor 'Browser' --- property '_defaultContext' closes the circle Are you passing a nested JSHandle? at JSON.stringify ()

这是我的代码(你可以忽略长的 XPath 选择器):

This is my code (you can ignore the long XPath selector):

let lastNameIn = await page.$x('//*[contains(translate(@placeholder,"abcdefghijklmnopqrstuvwxyz","ABCDEFGHIJKLMNOPQRSTUVWXYZ"), "LAST") and contains(translate(@placeholder,"abcdefghijklmnopqrstuvwxyz","ABCDEFGHIJKLMNOPQRSTUVWXYZ"), "NAME"))]')

lastname = "test"

await page.evaluate((lastname, lastNameIn) => { 
    el => el.value = lastname, lastNameIn[0]    
}, lastname, lastNameIn)

推荐答案

你应该只给 el.value 赋值一个值,然后在第一个参数位置标记你要计算的元素:lastNameIn[0],作为第二个参数,您可以将依赖变量:lastName 添加到 pageFunction.

You should assign only one value to el.value, then mark the element you want to evaluate at the first argument position: lastNameIn[0], as a second argument you can add the dependency variable: lastName to the pageFunction.

参见:page.evaluate, page.evaluate(pageFunction[, ...args]).

const lastNameIn = await page.$x("...");
const lastname = "test";

await page.evaluate((el, lastname) => { 
  el.value = lastname; 
}, lastNameIn[0], lastname);

这篇关于Puppeteer:如何在评估函数中使用 XPath 和外部变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆