首页 > 解决方案 > 从 Selenium 和 JAVA 中的特定标签获取内容

问题描述

我面临以下问题,

考虑这段代码:

<div data-v-2f952c88="" class="text">
 <section data-v-3b70ad5b="" data-v-2f952c88="" data-content-provider="OTS" class="description__section">        
    SOMETHING
 </section>
</div>
<div data-v-1343242dd="" class="text">
 <section data-v-2232lfd="" data-v-3fgssder="" data-content-provider="HTB" class="description__section">
    SOMETING ELSE
  </section>
</div>

我如何使用 Selenium 在 Java 中从代码中存在的所有标签“data-content-provider”中提取所有内容,所以最后我可以有一个这样的字符串

字符串结果=“OTS,HTB”。

谢谢

标签: javaselenium

解决方案


// get all section elements
List<WebElement> sections = driver.findElements(By.tagName("section"));

// new empty list of strings
List<String> dataContentProviders = new ArrayList<String>();

// collect all the data-content-provider values to dataContentProviders 
for (WebElement section: sections) {
     dataContentProviders.add(section.getAttribute("data-content-provider");
}

推荐阅读