且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

是否可以单击页面上具有动态内容的每个元素?

更新时间:2023-12-03 08:05:58

是的,通常可以单击页面上的任何元素.即使没有标识它们的ID或类的元素也具有选择器.获取他们的选择器可能会更加复杂.

Yes, in general it is possible to click on any element on the page. Even elements without an ID or class that identifies them, have a selector. It might just be more complicated to get their selector.

下面是一个如何在Chrome浏览器中获取元素选择器的示例.我正在获取问题的第一个p元素的选择器.请注意,它也没有ID或类. document.querySelector('...')表明它可以正确识别该节点.

Below is an example how to get the selector of an element inside the Chrome browser. I'm getting the selector for the first p element of your question. Note, that it also does not have an ID or class. The document.querySelector('...') shows that it correctly identifies the node.

即使元素是动态生成的,它也具有选择器,但可能很难找到它.您可能需要检查此页面 CSS选择器的可能性.

Even if the element is generated dynamically it has a selector, it might just be harder to find it. You might want to check this page on the various possibilities of CSS selectors.

如果该元素不容易识别,您还可以考虑使用该元素的内容进行识别是否更有意义.例如,您可以使用XPath表达式在内部使用特定文本查找元素.

If the element is not easy to identify you can also think whether it makes more sense to use the content of the element to identify it. You can for example use an XPath expression to find an element with a specific text inside.

有了选择器后,您可以使用 elementHandle.click 这样的功能:

After you have a selector, you can use the page.click function or the elementHandle.click function like this:

示例:查询所有元素,对其进行迭代并依次单击

Example: Query all elements, iterate over them and click one after another

const elements = await page.$$('div.example a');
for (const element of elements) {
    await element.click();
}

示例:只需单击两个元素

await page.click('div.selector a.example');
await page.click('div.selector a.example2');

点击页面上的所有元素

如果您实际上要单击页面上的所有元素,则可以使用*选择器:

Clicking all elements on the page

If you actually want to click all elements on a page, you can use the * selector:

const elements = await page.$$('*');

您可以遍历此数组,但是请注意,它还包含script标签,div容器,htmlheadbody等元素,以及不可单击的元素.此外,某些元素(如a标记)在单击后可能会发出导航请求.其他元素(例如按钮)甚至可能在DOM中添加或删除某些内容.

You could iterate over this array, but be aware that this also contains elements like script tags, div containers, html, head, body and also elements which are not clickable. In addition, some elements (like a tags) might do a navigation request after they are clicked. Other elements (like buttons) might even add or remove something from the DOM.