我正在嘗試根據引數列印表中的所有列值。如果引數匹配,則應列印所有列值。這在我下面的代碼中沒有發生。
public class DynamicTableHandling extends DriverFactory {
static String company = "ABB India Ltd.";
public static void main(String[] args) {
init_driver("chrome");
driver.get("https://money.rediff.com/sectors/bse/power");
extractTableValues(company);
}
public static void extractTableValues(String company) {
//print all the column values from the table when the company name provided has matched//
List<WebElement> tableRow = driver.findElements(By.xpath("//table[@class='dataTable']/tbody/tr"));
for (int row = 0; row < tableRow.size(); row ) {
WebElement colData = tableRow.get(row);
List<WebElement> tableCol = colData.findElements(By.tagName("td"));
for (int col = 0; col < tableCol.size(); col ) {
String result = tableCol.get(col).getText();
if (company.equals(result.trim())) {
System.out.print(result " | ");
break;
}
}
}
}
}
輸出-- ABB India Ltd. |
uj5u.com熱心網友回復:
當前方法extractTableValues的復雜度為O(n^2). 您可以O(n)通過制作動態 xpath 來顯著優化。
您的有效代碼:
public static void extractTableValues(String company) {
List<WebElement> tds = driver.findElements(By.xpath("//a[contains(.,'" company "')]//ancestor::tr//td"));
for (WebElement td : tds) {
System.out.println(td.getAttribute("innerText"));
}
}
輸出:
ABB India Ltd.
A
2090.10
2084.35
5.75
0.28
或使用 Java 1.8:
public static void extractTableValues(String company) {
List<WebElement> tds = driver.findElements(By.xpath("//a[contains(.,'" company "')]//ancestor::tr//td"));
tds.stream().forEach(td -> {System.out.println(td.getText());});
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/468305.html
上一篇:元素存在時硒找不到元素
下一篇:Selenium:沒有這樣的元素例外出現在這個http://www.salesfoce.com/即使認為元素存在
