【问题标题】:How to find an element by text and click on it using puppeteer js如何通过文本查找元素并使用 puppeteer js 点击它
【发布时间】:2020-10-28 18:46:49
【问题描述】:

我想找到一个包含文本的特定元素并单击它。 有一个元素,如: <a class="name" href="/main/photo/qwweqqeqwe"> This text </a> class="name"的元素很多,我需要点击包含某些文字的元素

【问题讨论】:

    标签: javascript jquery text click puppeteer


    【解决方案1】:

    类似这样的:

    const puppeteer = require('puppeteer');
    
    (async function main() {
      try {
        const browser = await puppeteer.launch({ headless: false, defaultViewport: null });
        const [page] = await browser.pages();
    
        await page.goto('https://example.org/');
    
        const [element] = await page.$x('//a[text()="More information..."]');
        // For partial match:
        // const [element] = await page.$x('//a[contains(text(), "More")]');
        await element.click();
      } catch (err) {
        console.error(err);
      }
    })();
    

    【讨论】:

    • 是否有可能以某种方式仅使用一个单词找到一个元素,例如,如果该元素由两个单词组成?
    • 部分匹配见代码中的注释:const [element] = await page.$x('//a[contains(text(), "More")]');
    猜你喜欢
    • 2020-09-29
    • 1970-01-01
    • 1970-01-01
    • 2012-12-27
    • 1970-01-01
    • 2020-01-01
    • 2020-05-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多