And*_* D_ 1 javascript node.js puppeteer
我正在与 Puppeteer 合作并尝试下载图像。在 Chrom 开发工具控制台上,这会返回我想要的内容:
document.querySelector('.photo img').getAttribute('src')
Run Code Online (Sandbox Code Playgroud)
但使用 Puppeteer 评估函数相同的代码:
let imageSrc = await page.evaluate(() => {
return document.querySelector('.photo img').getAttribute('src');
});
Run Code Online (Sandbox Code Playgroud)
抛出错误:
error: Error: Evaluation failed: TypeError: Cannot read property 'getAttribute' of null
Run Code Online (Sandbox Code Playgroud)
知道为什么会发生这种情况吗?
小智 6
可能你必须等待元素。
await page.waitForSelector('.photo img');
const imgSrc = await page.$eval('.photo img', (el) => el.getAttribute('src'));
Run Code Online (Sandbox Code Playgroud)
或者
await page.waitForSelector('.photo img');
const imgSrc = await page.$eval('.photo img', (el) => el.src); // Not sure if gonna work
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1848 次 |
| 最近记录: |