迭代Web元素列表并获取两个或多个值

时间:2017-12-19 00:42:53

标签: java selenium selenium-webdriver

我需要迭代到web元素列表以获取名称和标题的文本

示例:

<ul id="GalleryViewInner" class="gv-ic">
<li id="item3ad73f1239" class="sresult gvresult">
    <div id="1"
        <span id="span1">5,000USD</span>
    </div>  
    <div id="2"
        <td id="td1">TITLE</td>
    </div>
<li id="item3ad73f1239" class="sresult gvresult">
<li id="item3ad73f1239" class="sresult gvresult">
<li id="item3ad73f1239" class="sresult gvresult">
<li id="item3ad73f1239" class="sresult gvresult">
</ul>

迭代ul列表:

List<WebElement> allElements = driver.findElements(By.xpath("//ul[@id='GalleryViewInner']/li"));

    Iterator<WebElement> iter = allElements.iterator();

    while (iter.hasNext()) {
        WebElement PRICE = iter.next();

        PRICE.getTxt();
        TITLE.getText();

        }

在每次迭代中,我需要从每个“li”

中获取两个或更多元素

我需要获取所有li元素的价格和名称

爪哇

Selenium Webdriver

2 个答案:

答案 0 :(得分:1)

将您上面展示的网络元素与上面的内容相提并论,其他<li></li>是相同的

<ul id="GalleryViewInner" class="gv-ic">
<li id="item3ad73f1239" class="sresult gvresult">
    <div id="1"
        <span id="span1">5,000USD</span>
    </div>  
    <div id="2"
        <td id="td1">TITLE</td>
    </div>
</li>
<li></li>
</ul>

Asumming价格为<span></span>,ID为“span1”,名称为<td></td>,ID为“td1”我将采用此方法

List<WebElement> liElements = driver.findElements(By.xpath("//ul[@id='GalleryViewInner']/li"));
for(WebElement li : liElements){
    WebElement spanPrice = li.findElement(By.id("span1"));
    String price = spanPrice.getText();
    WebElement tdName = li.findElement(By.id("td1"));
    String name = tdName.getText();
}

答案 1 :(得分:0)

根据您提供的HTML获取nametitle的文字,您可以使用以下代码块:

List<WebElement> all_span_elements = driver.findElements(By.xpath("//ul[@id='GalleryViewInner']//li/div/span"));
List<WebElement> all_td_elements = driver.findElements(By.xpath("//ul[@id='GalleryViewInner']//li//following::div[2]/td"));
List<String> names = new ArrayList<>();
List<String> titles = new ArrayList<>();
for(WebElement ele1:all_span_elements)
    names.add(ele1.getAttribute("innerHTML"));
for(WebElement ele2:all_td_elements)
    titles.add(ele2.getAttribute("innerHTML"));
for(int i=0; i<all_span_elements.size(); i++)
    System.out.println("Medicine Name is : " + names.get(i) + "and Title is : " + titles.get(i));