简体   繁体   English

如何根据 textContent 从一组元素中单击一个元素 - Puppeteer

[英]How to click an element from a group of elements based on the textContent - Puppeteer

I want to click on a selected element matching the given text using puppeteer.我想使用 puppeteer 单击与给定文本匹配的选定元素。

The below javascript code is working fine in the browser console.下面的 javascript 代码在浏览器控制台中运行良好。

let menuitems = document.querySelectorAll('a[role=menuitem]');

for(i=0; i < menuitems.length; i++){

  if((menuitems[i].textContent).includes("My Content")){
     menuitems[i].textContent.click()

     console.log("found");
   }
}

May I know how can I do this using puppeteer?我可以知道如何使用 puppeteer 执行此操作吗?

The below code snippet has a function that uses puppeteer to go to a page and clicks a given element (assuming you entered what you need).下面的代码片段有一个函数,它使用 puppeteer 转到页面并单击给定元素(假设您输入了所需的内容)。 Please read comments throughout to see what you need to add.请通篇阅读评论以了解您需要添加的内容。

Puppeteer has some amazing API doc's on their git-hub. Puppeteer 在他们的 git-hub 上有一些很棒的API 文档 Puppeteer is a lot of fun when used to it's full potential. Puppeteer 当习惯了它的全部潜力时会很有趣。 It can do practically anything a normal user can perform on a browser.它几乎可以执行普通用户在浏览器上可以执行的任何操作。 Have fun!玩得开心!

 //Include puppeteer module const puppeteer = require('puppeteer'); //Function must be async to "await" for page results const clickElm = async () => { let browser = await puppeteer.launch(); //If you want to run puppeteer headless (be able to see whats happening) pass the set "headless" to "false" //let browser = await puppeteer.launch({headless: false}) let page = await browser.newPage(); //Enter your desired URL below await page.goto('<your_desired_url>'); //Evaluate the page with page.evaluate() await page.evaluate(() => { let menuitems = document.querySelectorAll('a[role=menuitem]') //For each menu item click (assuming the element is clickable) menuitems.forEach(item => { if(item.textContent.includes('My Content')){ item.click() } }) }) } clickElm();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM