java - 如何使用 Selenium Webdriver 在 HTML 的上行查找类名

标签 java html selenium selenium-webdriver webdriver

我有以下 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"然后检查类值是否包含 currentoutside

我使用 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是系统随机生成的。据我所知,我们不能使用containscssSelector

请问有什么建议吗?谢谢。

最佳答案

您可以使用//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/

相关文章:

javascript - 保存后自动更新时如何识别 Selenium 页面中的元素?(自动化相关)

selenium - 守夜人 : Basic auth with access_key not working

java - 如何将具有小数、负小数的字符串解析为整数?

java - 更新 TreeMap 中的对象 (Java)

Java 图形用户界面 : How do I have more than one button on a row using GridBagLayout

java - 自定义适配器,选中项背景

html - 为什么 "div"不会随着其中的内容展开?

html - Div 可见但被忽略

java - 在 JBoss 5.1 中设置 user.dir 系统属性

html - 在 TD 内将 DIV 与同一行上的其他元素对齐