【问题标题】:How to select inner text of cousin using puppeteer如何使用 puppeteer 选择表弟的内部文本
【发布时间】:2023-03-23 04:50:01
【问题描述】:

我正在尝试根据表亲的字符串值获取电话号码。

我的目标是搜索“所有者”并最终得到电话号码的值。

<div>
    <h3>
        <a href="#">Owner</a>
    </h3>
    <p>
        (555) 555-5555
    </p>
</div>

这是我目前所拥有的,但我不断收到undefined。你能解释一下我做错了什么吗?

console.log(await this.page.$("//h3[contains(a, 'Owner')]/../p").innerText);

【问题讨论】:

    标签: puppeteer playwright


    【解决方案1】:

    有一些问题:

    1. page.$() 需要 CSS 选择器,而不是 XPath。
    2. page.$x() 将返回一个带有 ElementHandle-s 的数组。
    3. ElementHandle-s 的属性与 DOM 元素不同,我们需要使用更复杂的 API 来获取它们。
    4. 我无法让 puppeteer 创建一个带有 '#' href 的 a 元素,只有完整的 URL,但这可能是一个测试用例问题。

    这对我有用:

    const html = `
      <!doctype html>
      <html>
        <head><meta charset='UTF-8'><title>Test</title></head>
        <body>
          <div>
              <h3>
                  <a href="http://example.com/">Owner</a>
              </h3>
              <p>
                  (555) 555-5555
              </p>
          </div>
        </body>
      </html>`;
    
    const puppeteer = require('puppeteer');
    
    (async function main() {
      try {
        const browser = await puppeteer.launch();
        const [page] = await browser.pages();
    
        await page.goto(`data:text/html,${html}`);
    
        const data = await (
          await (
            await page.$x("//h3[contains(a, 'Owner')]/../p")
          )[0].getProperty('innerText')
        ).jsonValue();
        console.log(data);
    
        await browser.close();
      } catch (err) {
        console.error(err);
      }
    })();
    

    【讨论】:

      猜你喜欢
      • 2019-11-04
      • 2021-01-10
      • 2010-12-11
      • 2012-08-17
      • 1970-01-01
      • 2016-09-30
      • 1970-01-01
      • 2020-07-23
      • 2018-08-13
      相关资源
      最近更新 更多