1

I want to click a link with certain text using Puppeteer.

<a class="text-major ev-pick-this-event" 
    href="/cgi-bin/ncommerce3/SEGetEventInfo?ticketCode=GS%3AAMTX%3AHUSKERS%3ASLP2%3A&amp;linkID=BQFN80-AMTX&amp;shopperContext=&amp;pc=&amp;caller=&amp;appCode=&amp;groupCode=SLP&amp;cgc=&amp;dataAccId=129&amp;locale=en_US&amp;siteId=ev_BQFN80-AMTX">
    HUSKERS - SLP2 - Ranges
</a>
Adriano
  • 3,788
  • 5
  • 32
  • 53
Tim
  • 15
  • 3
  • try this one https://browsee.io/blog/puppeteer-how-to-find-a-link-element-with-a-certain-text/ – iurii Oct 30 '19 at 22:29
  • https://stackoverflow.com/questions/47407791/puppeteer-click-on-element-with-text – domlas Oct 31 '19 at 12:47
  • Does this answer your question? [Puppeteer: Click on element with text](https://stackoverflow.com/questions/47407791/puppeteer-click-on-element-with-text) – domlas Oct 31 '19 at 12:48

2 Answers2

2

It can be done with XPath's contains() and text() methods, for example:

const [link] = await page.$x('//a[contains(text(), "certain text")]') // returns an array, as the first element will be used it can be destructured
await link.click()
theDavidBarton
  • 7,643
  • 4
  • 24
  • 51
-1
    let click = await page.evaluate(() => {
      try {
        const getText = e => (e ? e.innerText.trim() : '')
        let links = document.querySelectorAll('nav a')
        for (let i = 0, n = links.length; i < n; i++) {
          if (getText(links[i]) === 'Home') {
            links[i].click()
            return getText(links[i])
          }
        }
      } catch (e) {
        return e.toString()
      }
    })
    console.log({ click })
  • Please improve this CodeOnly-Answer by adding an Explanation what it does and why it helps the OP. – BigM Nov 21 '19 at 08:00