gpt4 book ai didi

javascript - 如何在 puppeteer 中访问全局变量

转载 作者:行者123 更新时间:2023-12-04 03:45:22 29 4
gpt4 key购买 nike

在这个示例代码中,当它读取数组 contactListj 时,它说两者都没有定义,有什么问题吗?


const { join } = require('path');
const puppeteer = require('puppeteer');

(async () => {

// 1. Launch the browser
const browser = await puppeteer.launch({
"args": [
'--remote-debugging-port=9222'
],
"defaultViewport": {
"height": 1080,
"width": 1920
},
"headless": false
});

// 2. Open a new page
const page = await browser.newPage();

// 3. Navigate to URL
await page.goto('https://');

await new Promise(r => setTimeout(r, 10000));
console.log('Ready');

var contactList = ['cesar','gab','777','81411579','34353'];
var fLen = contactList.length;
var j = 0;

for (i = 0; i < fLen; i++) {

await page.evaluate(() => {

function searchContact(contact_name = "") {
//search = document.querySelector('#side > div._1Ra05 > div > label > div > div._1awRl.copyable-text.selectable-text');
search = document.querySelector('#side > div._1Ra05 > div > label > div > div._1awRl.copyable-text.selectable-text');
}
j++;
searchContact(contactList[j]);

}
}

最佳答案

查看 page.evaluate(pageFunction[,...args]) 的 Puppeteer 文档.它指出:

pageFunction <function|string> Function to be evaluated in the page context

注意(粗体)“在页面上下文中评估”。页面上下文中不存在变量 jcontactList

幸运的是,Puppeteer 有一种从页面上下文调用服务器端代码的方法 page.exposeFunction(name, puppeteerFunction)

The method adds a function called name on the page's window object. When called, the function executes puppeteerFunction in node.js and returns a Promise which resolves to the return value of puppeteerFunction.

对于您的用例,它看起来类似于以下内容:

const puppeteer = require('puppeteer');

(async function()
{
const browser = await puppeteer.launch({
headless: false,
args: [
"--no-sandbox", // I needed these args for it to run on my machine, you probably don't need them.
"--disable-setuid-sandbox"
]
});
const page = await browser.newPage();
const contacts = ["Charlie", "Carl", "Dennis", "Conrad"];
await page.exposeFunction("getContacts", function()
{
return contacts;
});
await page.exposeFunction("addContact", function(contact)
{
contacts.push(contact);
});
await page.evaluate(async function()
{
await addContact("Henry");
await addContact("Olav");
const contacts = await getContacts();
contacts.forEach(function(contact)
{
const div = document.createElement("div");
div.innerHTML = contact;
document.body.appendChild(div);
});
});
console.log("Contacts after evaluating page function: ", contacts.join(", "));
})()

请注意,这是一个玩具示例,虽然是一个完整且可运行的示例。您应该能够从中找出其余部分。您在 OP 示例中发布的代码没有多大意义(即无限递归函数 searchContact()),因此您只需要根据您的用例进行调整。

关于javascript - 如何在 puppeteer 中访问全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65266253/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com