【问题标题】:Unable to read <p> text under <h3> using selenium无法使用 selenium 读取 <h3> 下的 <p> 文本
【发布时间】:2018-07-27 14:20:28
【问题描述】:

我有一个类似的 html 代码:

<h3> Some Heading </h3>
<p> Some String </p>
<p> more string </p>
<h3> Other heading</h3>
<p> some text </p>

我正在尝试访问Some Stringmore stringsome text。使用 java,我尝试像这样访问:

List<WebElement> h3Tags = driver.findElements(By.tagName("h3"));

List<WebElement> para = null;

WebElement bagInfo = h3Tags.get(0);  //reads first h3
if(bagInfo.getText().contains("carry-on") || bagInfo.getText().contains("Carry-on")){
        para = AutoUtils.findElementsByTagName(bagInfo, "p");
        System.out.println(para.get(0).getText());  //Null pointer here 
}

bagInfo = h3Tags.get(1);
if(bagInfo.getText().contains("checked") || bagInfo.getText().contains("Checked")){
        para = AutoUtils.findElementsByTagName(bagInfo, "p");
        System.out.println(para.get(0).getText());  //Null pointer here too
}

尝试xpath"h3['/p']" 一样,但仍然没有运气。访问这些 &lt;p&gt; 字符串的最佳方式是什么?

【问题讨论】:

  • 带 xpath //h3/following::p

标签: java selenium selenium-webdriver automation selenium-firefoxdriver


【解决方案1】:

尝试 xpath //h3/following-sibling::p 匹配所有 3 个段落

还请注意,您的 XPath h3['/p'] 不起作用,因为这意味着 返回作为 DOM 根节点的 h3 节点。谓词 ['/p'] 将始终返回 True,因为非空字符串(在您的情况下为 '/p')始终为 True

【讨论】:

    【解决方案2】:

    要访问 Some Stringmore stringsome text,您可以使用以下 Locator Strategy

    • 使用文本作为Some String

      访问节点
      By.xpath("//h3[normalize-space()='Some Heading']//following::p[1]")
      
    • 使用文本作为更多字符串

      访问节点
      By.xpath("//h3[normalize-space()='Some Heading']//following::p[2]")
      
    • 使用文本访问节点作为一些文本

      By.xpath("//h3[normalize-space()='Other heading']//following::p[1]")
      
    • 找到这些元素后,您可以使用 getAttribute("innerHTML") 方法提取节点内的文本。

    【讨论】:

      猜你喜欢
      • 2022-08-14
      • 2015-12-22
      • 1970-01-01
      • 2020-06-01
      • 2019-09-02
      • 2019-06-15
      • 2021-09-21
      • 2012-06-04
      • 1970-01-01
      相关资源
      最近更新 更多