Puppeteer:如何在评估函数中使用 XPath 和外部变量?

Puppeteer: How to use XPath and external Variable in evaluate function?

我尝试在 Puppeteer 的求值函数中使用 XPath 和外部变量,但出现问题:

我刚收到这个错误:

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 选择器):

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],作为第二个参数,您可以添加依赖变量:lastNamepageFunction.

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

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

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