我开始使用pupeteer和node并使用vscode。我正在尝试登录网站并刮擦桌子。到目前为止,我有:
(async () => {
const browser = await puppeteer.launch({
headless: false,
});
var page = await browser.newPage();
await page.goto('thesite.com/login/');
await page.click(USERNAME_SELECTOR);
await page.keyboard.type(CREDS.username);
await page.click(PASSWORD_SELECTOR);
await page.keyboard.type(CREDS.password);
await page.click(BUTTON_SELECTOR);
await page.waitForNavigation();
const TABLE_ROW_SELECTOR = '.gv-container.gv-container-133 > table > tbody';
await page.waitForSelector(TABLE_ROW_SELECTOR);
await page.waitForSelector(TABLE_ROW_SELECTOR);
await page.screenshot({ path: 'example.png' });
const data = await page.evaluate(() => document.querySelectorAll(TABLE_ROW_SELECTOR));
await browser.close();
})();
这主要是有效的。该脚本似乎可以执行到:
const data = await page.evaluate(() => document.querySelectorAll(TABLE_ROW_SELECTOR));
给出标题错误的地方。上面的屏幕截图没有显示屏幕截图下方的表格。当我输入
document.querySelectorAll(TABLE_ROW_SELECTOR));
进入devtools控制台,我得到了预期的html。我在做什么错了?
编辑:
在我的控制台中,我看到了一个对象列表,但据我所知,没有任何值。这是最好的对象
0:Object {}
__proto__:Object {constructor: , __defineGetter__: , __defineSetter__: , …}
__defineGetter__:function __defineGetter__() { … }
__defineSetter__:function __defineSetter__() { … }
__lookupGetter__:function __lookupGetter__() { … }
__lookupSetter__:function __lookupSetter__() { … }
constructor:function Object() { … }
hasOwnProperty:function hasOwnProperty() { … }
No debug adapter, can not send 'variables'
isPrototypeOf:function isPrototypeOf() { … }
No debug adapter, can not send 'variables'
“没有调试适配器,无法发送'变量'”是什么意思?
答案 0 :(得分:2)
page.evaluate()
的函数参数在文档(浏览器)上下文中执行,并且无法访问Node.js脚本的变量。您需要按值传输这些变量:
const data = await page.evaluate(SELECTOR => document.querySelectorAll(SELECTOR), TABLE_ROW_SELECTOR);