我需要迭代到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元素的价格和名称
Java的
Selenium Webdriver
假设您的网络元素在上面向我们展示,其他<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();
}
根据您提供的HTML
获取name
和title
的文本,您可以使用以下代码块:
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));