Click visible elements using puppeteer
I am trying to click a number of elements in in a page, but only if they are visible. This was quite easy using selenium (using is_displayed
), but I can't seem to find a way in puppeteer. I was trying to use something like
try {
await page
.waitForSelector(id, visible=true, timeout=0)
.then(() => {
element.click()
});
...
But this does not working if it is a simple element like :
<a class="cookie-close" href="#">
OK
</a>
I also can't seem to see a way to do it using the element.click
method in puppeteer.
与Selenium类似,正确答案也是使用Puppeteer的waitForSelector,它可以测试DOM元素的存在和可见性。
try {
// Will throw err if element is not present and visible.
await chromePage.waitForSelector("div.hello", {
visible: true
});
await chromePage.click("div.hello");
} catch(err) {
console.log(err);
}
You should use page.click() for effecting a click.
See page.click(selector, [options]) in Puppeteer's API docs: https://github.com/GoogleChrome/puppeteer/blob/HEAD/docs/api.md#pageclickselector-options
不知道这是否是最有效的方法,但您可以尝试如下所示:
// returns null if element not present
let element = await page.evaluate(() => {
return document.querySelector(id);
});
// use jQuery to check if element is not hidden
if (element && !$(element).is(':hidden') {
await page.click(id);
}
链接地址: http://www.djcxy.com/p/83590.html
上一篇: jQuery替代document.activeElement
下一篇: 点击可见元素使用木偶