我尝试单击下一页
按钮来迭代不同的页面,但是在单击
之后,脚本永远卡在那里,代码如下。
为什么waitForNavigation
永远不会完成?
async function main() {
const br = await pptr.launch({headless: false, defaultViewport: null});
const page = await br.newPage();
await page.goto(
'https://www.escentual.com/catalogsearch/result/?q=face',
{waitUntil: 'networkidle2'}
);
for (var i=0; i<10; ++i) { // click next-page button 10 times,
await Promise.all([
page.waitForNavigation({waitUntil: 'load', timeout: 100000}),
page.click('#adj-nav-container > div.category-products > div.toolbar > div > div.amount > div > ol > li.next > a'), // next-page css
]);
console.log(`waited, url=${page.url()}`);
}
await br.close();
}
main();
最佳答案
您尝试单击的元素顶部有一个覆盖层。您应该关闭该覆盖层或仅使用 HTMLElement.click
:
page.$eval('#adj-nav-container > div.category-products > div.toolbar > div > div.amount > div > ol > li.next > a', el => el.click())
或者,您可以只更改网站 URL 中的页码:
https://www.escentual.com/catalogsearch/result/index/?p=1&q=face
https://www.escentual.com/catalogsearch/result/index/?p=2&q=face
...
<小时/>
检测覆盖
这是检测元素是否位于覆盖层后面的一种方法。 document.elementFromPoint
获取一个坐标并返回该坐标的最顶层元素。我们通过 boundingBox()
获取所选元素的坐标方法,然后将其与该坐标的最顶部元素进行比较。如果它们相同,则意味着该元素不在覆盖层或其他元素后面。
示例:
let targetElement = await page.$('#adj-nav-container > div.category-products > div.toolbar > div > div.amount > div > ol > li.next > a');
let {x, y} = await targetElement.boundingBox();
let isOnTop = await page.evaluate((x,y, selectedElement) => {
let topElement = document.elementFromPoint(x,y);
return topElement === selectedElement;
}, x, y, targetElement);
if (isOnTop)
console.log("Element is not behind overlay");
关于javascript - waitForNavigation 无故挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60240768/