木偶-如何单击带有特定文本的链接

时间:2019-10-30 22:10:46

标签: puppeteer

我想使用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>

2 个答案:

答案 0 :(得分:1)

可以使用XPathcontains()text()方法来完成,例如:

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()

答案 1 :(得分:-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 })