我有以下 HTML 代码:
<!-- language: lang-html -->
<td class="Schedule-col details">
<td class="Schedule-col timeslots">
<div class="timeslots-container" style="opacity: 1; visibility: visible;">
<div class="timeslot d1422270000000 row0 col0 outside" data-time="1422270000000" style="width: 3.22581%;">
<div class="timeslot d1422356400000 row0 col1 outside" data-time="1422356400000" style="width: 3.22581%;">
<div class="timeslot d1422442800000 row0 col2 outside" data-time="1422442800000" style="width: 3.22581%;">
<div class="timeslot d1422529200000 row0 col3 outside" data-time="1422529200000" style="width: 3.22581%;">
<div class="timeslot d1422615600000 row0 col4 outside" data-time="1422615600000" style="width: 3.22581%;">
<input class="row0 col4 widget" type="text" autocomplete="off">
</div>
<div class="timeslot d1422702000000 row0 col5 current" data-time="1422702000000" style="width: 3.22581%;">
<input class="row0 col5 widget" type="text" autocomplete="off">
</div>
基本上我想找到 class="row0 col5 widget"
的元素,找到它后,我想在该 HTML 中上一层并找到 <div class="timeslot d1422702000000 row0 col5 current"
然后检查类值是否包含 current
或outside
。
我使用 Webdriver 编写此代码,并且可以找到该元素。
int ColIndex=5;
int RowIndex=0;
WebElement pointer = driver.findElement(By.cssSelector(".row"+RowIndex+".col1"+ColIndex+".widget"));
String xx=pointer.getAttribute("class");
System.out.println(xx);
使用此代码我可以找到元素 <input class="row0 col5 widget" type="text" autocomplete="off">
但我不知道如何上一层并找到 <div class="timeslot d1422702000000 row0 col5 current"
并检查它是否包含 current
或不。
我无法直接找到timeslot d1422702000000 row0 col5 current
因为号码d1422702000000
是系统随机生成的。据我所知,我们不能使用contains
在cssSelector
。
请问有什么建议吗?谢谢。
最佳答案
您可以使用//div[input[@class='row0 col5 widget']]
XPath 表达式:
WebElement div = driver.findElement(By.xpath("//div[input[@class='row0 col5 widget']]"));
String xx = div.getAttribute("class");
该表达式将与具有 class="row0 col5 widget"
的直接 input
子元素的 div
元素相匹配。
当然还有其他选择。例如,要继续您已开始的操作:
WebElement pointer = driver.findElement(By.cssSelector(".row"+RowIndex+".col1"+ColIndex+".widget"));
WebElement div = pointer.findElement(by.xpath(".."));
String xx = div.getAttribute("class");
其中 ..
将上升到直接父级。
关于java - 如何使用 Selenium Webdriver 在 HTML 的上行查找类名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29225364/