Selenium Webdriver - Fetching Table Data

后端 未结 7 1977
执笔经年
执笔经年 2021-02-04 08:03

I want to fetch data from tables in UI. I know about looping through rows and columns using \"tr\" and \"td\". But the one the table I have is something like this:



        
7条回答
  •  一向
    一向 (楼主)
    2021-02-04 08:39

    You don't need to loop through elements. Instead, use a ByChained locator.

    If you table looks like this:

    Col1Col2Col3
    datadatadata
    datadatadata
    datadatadata

    The locate like this:

    By tableBodyLocator = By.xpath(".//table/tbody");
    By headerRowLocator = By.xpath(".//tr[position()=1]");
    By dataRowsLocator = By.xpath(".//tr[not(position()=1)]");
    
    By headerRowLocator = new ByChained(tableBodyLocator, headerRowLocator);
    List weHeaders = driver.findElement(headerRowLocator)
           .findElements(By.xpath(".//th");
    List allRowData = driver.findElements(tableBodyLocator, dataRowsLocator);
    
    WebElement row1Data = allRowData.get(0);
    WebElement row2Data = allRowData.get(1);
    
    etc.
    

提交回复
热议问题