我有一个包含多行和多列的表。
HTML代码如下所示:
<!-- language: lang-html -->
<div id="ScheduleTable-01" class="widget Scheduletable suppress-errors Schedule-grid" data-widget="ScheduleTable">
<div class="grid-wrapper">
<table class="nostyles weekmode hourstype fullmonth" style="width: 100%;">
<thead>
<tbody>
<tr id="20631697" class="Schedule-row row0 20631697 key_AuthoriserId-1077_JobId-402704200_TaskId-CON_TsCode-35" data-row-index="0" data-job="402121200,Job XXX">
<tr id="-499545938" class="Schedule-row row1 -499545938 key_AuthoriserId-1077_JobId-A01200131S_TaskId-CON_TsCode-35" data-row-index="1" data-job="A01763431 Job YYY">
<tr id="-985929934" class="Schedule-row row2 -985929934 key_AuthoriserId-1277_JobId-I02010171S_TaskId-INT_TsCode-30" data-row-index="2" data-job="I02872371 S,Job ZZZ">
因为它是动态网页,所以每次加载页面时, Job YYY 都会被放置在不同的行索引中。因此,我想知道表 Job YYY 所在的哪一行。
我可以看到每一行都标有data-row-index
,这就是我想要的。
我正在考虑这个Selenium代码
<!-- language: lang-java -->
WebElement mainTable = driver.findElement(By.id("ScheduleTable-01"));
//I am not sure about this part below; findElements By ???
List<WebElement> tableRows = mainTable.findElements(By.tagName("tr"));
在这种情况下,我该如何找到行号?谢谢。
答案 0 :(得分:5)
您可以轻松使用getAttribute()
查看api doc。 getAtribute()
允许您获得atribute
个html
标记的//since you know the job
String job = "A01763431 Job YYY";
String dataRowIndex = driver.findElement(By.cssSelector("[data-job='" + job + "']")).getAttribute("data-row-index");
System.out.println(dataRowIndex);
值
iframe
打印
1
修改强>
好的,可能会有一些影响这个的事情。
该元素位于driver.switchTo().frame(driver.findElement(By.cssSelector("css for iframe")));
内
若然,请使用
String job = "A01763431 Job YYY";
By selector = By.cssSelector("#ScheduleTable-01 tr[data-job='" + job + "']");
WebElement element = new WebDriverWait(driver,10).until(ExpectedConditions.presenceOfElementLocated(selector));
String dataindex = element.getAttribute("data-row-index");
您正在寻找太快的元素。使用显式等待。
String job = "A01763431 Job YYY";
By selector = By.cssSelector("[data-job='" + job + "']");
List<WebElement> elements = new WebDriverWait(driver,10).until(ExpectedConditions.presenceOfAllElementsLocatedBy(selector));
int size = elements.size();
System.out.println(size);
提供的选择器返回了多个元素
{{1}}
查看返回了多少
答案 1 :(得分:1)
我在这里尝试了这个,它解决了这个问题。
<!-- language: lang-java -->
String job = "YYY";
WebElement table = driver.findElement(By.xpath("//tr[contains(@data-job,'"+job+"')]"));
String dataRowIndex = table.getAttribute("data-row-index");
System.out.println(dataRowIndex);
基本上我只是获取作业ID的一部分( YYY 而不是全名),并在xpath中使用contains()。
@Vivek @Saifur非常感谢您的建议。