使用Webdriver使用表头获取表中的所有单元格值

时间:2015-07-28 21:59:40

标签: selenium xpath selenium-webdriver css-selectors

Table contents

以下是表格的HTML代码:

我需要从标题前面的表中提取值为“商机”。 有人可以建议最好的方法前进,因为我可以提取价值,如果他们属于同一个表,但我需要帮助,当他们在两个不同的表,我需要寻找表机会,而不是从上表中提取数据。

2 个答案:

答案 0 :(得分:1)

当然,这是我对Java所需要的最佳解释。有任何问题,我会改变我的解决方案以适应他们。这开始于行和列的索引为0,0。

int row = 0, column = 1; //it's 1 to accommodate fogr the first thing you want being a 'th' tag
List<WebElement> tableRows = driver.findElements(By.className("dataRow"));//this gets all elements on your page with a class of dataRow (which are your tr's)
for(WebElement singleRow: tableRows) //this for loop increments each of these tr's
    {
        System.out.println(singleRow.findElement(By.xpath("th[1]/a[1]")).getText()); //I'll have to use an xpath here because I don't have time to play around with other solutions but it'll work
        System.out.println("Row: " + row + ", Column: " + column);
        List<WebElement> rowTDs = singleRow.findElements(By.tagName("td"));//this gets every td in the current tr and puts it into a list
        for(WebElement singleTD: rowTDs) //this increments through that list of td's
        {
            System.out.println(singleTD.getText()); //this gives you back the text contained in that cell
            System.out.println("Row: " + row + ", Column: " + column);
            column++; //increment the column counter
        }
        column=1; //reset the column
        row++; //increment the row counter
    }

编辑:似乎给出了请求的元素&#34; Saykiro&#34;几乎有它的权利,你可以在我的解决方案tableRows =替换这个,这可能是一个更简洁的方式来获得第二个表,但这是给我的:

WebElement table1 = driver.findElemen(By.id("001Z000000vrLQe_RelatedOpportunityList_title"));
WebElement table2 = table1.findElement(By.xpath("../../../../following-sibling::table"))
List<WebElement> tableRows = table2.findElements(By.className("dataRow"));

答案 1 :(得分:0)

对于你的情况:

var values = driver.FindElements(By.XPath("//*[table/tbody/tr/td/h3[text()='Opportunities']]/table[2]//td[@class=' dataCell ']")).Select(a=>a.Text);

对于C#(获取单元格中的值列表):

-startup
plugins/org.eclipse.equinox.launcher_1.3.0.v20140415-2008.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.200.v20140603-1326
-product
org.eclipse.epp.package.jee.product
--launcher.defaultAction
openFile
--launcher.XXMaxPermSize
1024M
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
1024m
--launcher.defaultAction
openFile
--launcher.appendVmargs
-vmargs
-Dosgi.requiredJavaVersion=1.6
-Xms1024m
-Xmx1024m

你应该描述html的外部部分,这样我们就可以更好地构建xpath。