【问题标题】:How to get individual data from multiple different <p> elements inside a div如何从 div 内的多个不同 <p> 元素中获取单个数据
【发布时间】:2018-08-14 22:13:08
【问题描述】:

我正在尝试从包含多个段落元素的 div 中提取单个数据。

HTML:

<div class="details" itemscope itemtype="http://schema.org/Organization">
  <p class="details-organisation">
    <span itemprop="name">Test1</span>
  </p>

  <p class="details-block">
    <span itemscope itemtype="http://schema.org/Person">
      <span itemprop="name">
        John Doe
      </span>
    </span>
  </p>


  <p class="details-block">
    <span itemprop="telephone">
      +44(0)123456789
    </span>
  </p>


  <p class="details-block">
    <span itemprop="email">
      <a href="mailto:test@test123.com" data-event-category="Email a supplier" data-event-label="Test">test@test123.com</a>
    </span>
  </p>


</div>

例如,我正在尝试从“详细信息组织”中提取“Test1”文本。

我的代码:

    WebElement contactDetails = driver.findElement(By.className("details-organisation"));
    System.out.println(contactDetails.findElement(By.tagName("span")).getText());

运行此程序会打印出一个空行。

【问题讨论】:

  • 试试contactDetails.findElement(By.tagName("span")).getAttribute("innerHTML")

标签: java html selenium-webdriver


【解决方案1】:

当您通过

提取了一个网络元素时
WebElement contactDetails = driver.findElement(By.className("details-organisation"));
// contactDetails has a valid and an identifiable Web Element

您可以简单地使用打印文本

System.out.println(contactDetails.getText());

即使在此之后您也没有得到输出,可能是识别包含文本的标签存在问题,因为它不是包含文本的 paragraph 标签,而是span 标记。

您可以将 Web Element 行更改为

WebElement contactDetails = driver.findElement(By.xpath("//span[@class = 'details-organisation']/span/span"));

然后继续获取前面提到的文本。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-06
    • 2019-11-09
    • 1970-01-01
    • 2016-08-07
    • 1970-01-01
    • 2021-09-04
    • 2012-08-17
    相关资源
    最近更新 更多