使用Selenium迭代在桌面上

时间:2018-01-12 10:38:10

标签: java selenium xpath web-scraping

我不明白为什么x-path没有在桌面上工作。我试图从我找到xpath的网站上找到它,但Eclipse告诉我:

  

"无法找到带有xpath"的元素。

我应该用另一种方式在表中找到xpath吗?

网站网址:https://www.oferty.net/mieszkania/szukaj?ps%5Blocation%5D%5Btype%5D=1&ps%5Btype%5D=1&ps%5Btransaction%5D=1&ps%5Blocation%5D%5Btext%5D=dolno%C5%9Bl%C4%85skie

我尝试阅读一个例子:

String urlwyniki ="https://www.oferty.net/mieszkania/szukaj?ps%5Blocation%5D%5Btype%5D=1&ps%5Btype%5D=1&ps%5Btransaction%5D=1&ps%5Blocation%5D%5Btext%5D=dolno%C5%9Bl%C4%85skie";
driver.get(urlwyniki);
String xpathResult = "//html/body/div[2]/div[4]/div[2]/div[2]/div/div[2]/div[5]/table/tbody/tr[5]/td";
String sCellValue = driver.findElement(By.xpath(xpathResult)).getText();
System.out.print(sCellValue);

我做错了什么?

1 个答案:

答案 0 :(得分:1)

找到以下代码以迭代表中的所有单元格值。它可能对你有帮助。

String urlwyniki ="https://www.oferty.net/mieszkania/szukaj?ps%5Blocation%5D%5Btype%5D=1&ps%5Btype%5D=1&ps%5Btransaction%5D=1&ps%5Blocation%5D%5Btext%5D=dolno%C5%9Bl%C4%85skie";
driver.get(urlwyniki);
String xpathResult = "//table/tbody/tr/td";
List<WebElement> rows = driver.findElements(By.xpath(xpathResult));
List<WebElement> cols=new ArrayList<WebElement>();
for(int i=0;i<rows.size();i++){
    System.out.print("Row value: "+i);
    cols=rows.get(i).findElements(By.tagName("td"));
    for(WebElement col:cols)
        System.out.print("cell value "+col.getText());
}