Come gestire le tabelle Web dinamiche in Selenium
⚡ Riepilogo intelligente
Gestire le tabelle Web dinamiche in Selenium WebDriver insegna come iterare, leggere e convalidare tabelle le cui righe o colonne cambiano in fase di esecuzione, coprendo identificazione, XPath, lookping, ed esempi.
Tabella Web in Selenium
Esistono due tipi di tabelle HTML pubblicate sul Web:
- Tabelle statiche: I dati sono statici, ovvero il numero di righe e colonne è fisso.
- Tabelle dinamiche: I dati sono dinamici, ovvero il numero di righe e colonne NON è fisso.
Come gestire la tabella dinamica in Selenium
Di seguito è riportato un esempio di tabella Web dinamica in Selenium per le vendite. In base ai filtri della data di input, il numero di righe verrà modificato. Quindi è di natura dinamica.
Gestire la tabella statica è semplice, ma gestire le tabelle dinamiche in Selenium è un po' difficile poiché le righe e le colonne non sono costanti.
Utilizzo di X-Path per individuare gli elementi della tabella Web
Before we locate web element, first let's understands-
Cos'è un elemento web?
Gli elementi Web non sono altro che elementi HTML come caselle di testo, pulsanti di scelta rapida a discesa, pulsanti di invio, ecc. Questi elementi HTML sono scritti con inizia a tag e termina con un fine etichetta.
Per esempio,
Il mio primo documento HTML.
Passaggi per ottenere il percorso X dell'elemento web che vogliamo individuare.
Passo 1) In Chrome, vai a https://demo.guru99.com/test/web-table-element.php
Passo 2) Right click on web element whose x-path is to be fetched. In our case, right click on "Company" Select Inspect option. The following screen will be shown -
Passo 3) Fare clic con il tasto destro sull'elemento Web evidenziato > Seleziona Copia -> Copia l'opzione x-path.
Passo 4) Use the copied X-path "//*[@id="leftcontainer"]/table/thead/tr/th [1]" in Selenium WebDriver per individuare l'elemento.
Esempio: recuperare il numero di righe e colonne dalla tabella Web dinamica
Durante la gestione della tabella Web dinamica in Selenium, non possiamo prevederne il numero di righe e colonne.
utilizzando Selenium driver web, possiamo trovare
- Numero di righe e colonne della tabella Web in Selenium
- X row or Y column's data.
Di seguito è riportato il programma per recuperare il numero totale di righe e colonne per la gestione della tabella Web Selenium:
import java.text.ParseException; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class Noofrowsandcols { public static void main(String[] args) throws ParseException { WebDriver wd; System.setProperty("webdriver.chrome.">driver","G://chromedriver.exe"); wd= new ChromeDriver(); wd.get("https://demo.guru99.com/test/web-table-">element.php"); //No.of Columns List <webelement> col = wd.findElements(By.xpath(".//*[@id=\"leftcontainer\"]/table/thead/tr/th")); System.out.println("No of cols are : " +col.size()); //No.of rows List <webelement> rows = wd.findElements(By.xpath(".//*[@id='leftcontainer']/table/tbody/tr/td[1]")); System.out.println("No of rows are : " + rows.size()); wd.close(); } }
Code Spiegazione:
- Here we have first declared Web Driver object "wd" &initialized it to chrome driver.
- We use List <WebElement> to total number of columns in "col".
- I comandi findElements restituiscono un elenco di TUTTI gli elementi che corrispondono al localizzatore specificato
- using findElements and X-path //*[@id=\"leftcontainer\"]/table/thead/tr/th we get all the columns
- Allo stesso modo, ripetiamo il processo per le righe.
Produzione:
Esempio: recuperare il valore della cella di una particolare riga e colonna della tabella dinamica
Let's assume we need 3rd row of the table and its second cell's data. See the table below-
Nella tabella sopra, i dati vengono aggiornati regolarmente dopo un certo periodo di tempo. I dati che proverai a recuperare saranno diversi dallo screenshot sopra. Tuttavia, il codice rimane lo stesso. Ecco un programma di esempio per ottenere il 3rd riga e 2nd column's data.
import java.text.ParseException; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; public class RowandCell { public static void main(String[] args) throws ParseException { WebDriver wd; System.setProperty("webdriver.chrome.">driver","G://chromedriver.exe"); wd= new ChromeDriver(); wd.get("https://demo.guru99.com/test/web-table-">element.php"); wd.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); WebElement baseTable = wd.findElement(By.tagName("table")); //To find third row of table WebElement tableRow = baseTable.findElement(By.xpath("//*[@id=\"leftcontainer\"]/table/tbody/tr[3]")); String rowtext = tableRow.getText(); System.out.println("Third row of table : "+rowtext); //to get 3rd row's 2nd column data WebElement cellIneed = tableRow.findElement(By.xpath("//*[@id=\"leftcontainer\"]/table/tbody/tr[3]/td[2]")); String valueIneed = cellIneed.getText(); System.out.println("Cell value is : " + valueIneed); wd.close(); } }
Code Spiegazione:
- Table is located using locator property "tagname".
- utilizzando XPath "//*[@id=\"leftcontainer\"]/table/tbody/tr[3]" find the 3rd row e ne ottiene il testo utilizzando la funzione getText()
- Using Xpath "//*[@id=\"leftcontainer\"]/table/tbody/tr[3]/td[2]" find the 2nd cell in 3rd row e ne ottiene il testo utilizzando la funzione getText()
Produzione :
Esempio: ottenere il massimo di tutti i valori in una colonna della tabella dinamica
In questo esempio, otterremo il massimo di tutti i valori in una particolare colonna.
Refer the following table -
Ecco il codice
import java.text.ParseException; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.text.NumberFormat; public class MaxFromTable { public static void main(String[] args) throws ParseException { WebDriver wd; System.setProperty("webdriver.chrome.">driver","G://chromedriver.exe"); wd= new ChromeDriver(); wd.get("https://demo.guru99.com/test/web-table-">element.php"); String max; double m=0,r=0; //No. of Columns List <webelement> col = wd.findElements(By.xpath(".//*[@id='leftcontainer']/table/thead/tr/th")); System.out.println("Total No of columns are : " +col.size()); //No.of rows List <webelement> rows = wd.findElements(By.xpath (".//*[@id='leftcontainer']/table/tbody/tr/td[1]")); System.out.println("Total No of rows are : " + rows.size()); for (int i =1;i<rows.size();i++) { max= wd.findElement(By.xpath("html/body/div[1]/div[5]/table/tbody/tr[" + (i+1)+ "]/td[4]")).getText(); NumberFormat f =NumberFormat.getNumberInstance(); Number num = f.parse(max); max = num.toString(); m = Double.parseDouble(max); if(m>r) { r=m; } } System.out.println("Maximum current price is : "+ r); } } </webelement></webelement>
Code Spiegazione:
- Using chrome driver we locate the web table and get total number of row using XPath ".//*[@id='leftcontainer']/table/tbody/tr/td[1]"
- Utilizzando il ciclo for, iteriamo sul numero totale di righe e recuperiamo i valori uno per uno. Per ottenere la riga successiva utilizziamo (i+1) in XPath
- Confrontiamo il vecchio valore con il nuovo valore e il valore massimo viene stampato alla fine del ciclo for
Produzione
Esempio: ottenere tutti i valori di una tabella dinamica
Considera la seguente tabella: https://demo.guru99.com/test/table.html
Il numero di colonne per ciascuna riga è diverso.
Qui la riga numero 1, 2 e 4 ha 3 celle, la riga numero 3 ha 2 celle e la riga numero 5 ha 1 cella.
Dobbiamo ottenere i valori di tutte le celle
Ecco il codice:
import java.text.ParseException; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import java.util.concurrent.TimeUnit; import org.openqa.selenium.chrome.ChromeDriver; public class NofRowsColmns { public static void main(String[] args) throws ParseException { WebDriver wd; System.setProperty("webdriver.chrome.">driver","G://chromedriver.exe"); wd = new ChromeDriver(); wd.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); wd.get("https://demo.guru99.com/test/table.html"); //To locate table. WebElement mytable = wd.findElement(By.xpath("/html/body/table/tbody")); //To locate rows of table. List < WebElement > rows_table = mytable.findElements(By.tagName("tr")); //To calculate no of rows In table. int rows_count = rows_table.size(); //Loop will execute till the last row of table. for (int row = 0; row < rows_count; row++) { //To locate columns(cells) of that specific row. List < WebElement > Columns_row = rows_table.get(row).findElements(By.tagName("td")); //To calculate no of columns (cells). In that specific row. int columns_count = Columns_row.size(); System.out.println("Number of cells In Row " + row + " are " + columns_count); //Loop will execute till the last cell of that specific row. for (int column = 0; column < columns_count; column++) { // To retrieve text from that specific cell. String celtext = Columns_row.get(column).getText(); System.out.println("Cell Value of row number " + row + " and column number " + column + " Is " + celtext); } System.out.println("-------------------------------------------------- "); } } }
Code Spiegazione:
- rows_count fornisce il numero totale di righe
- per ogni riga otteniamo il numero totale di colonne utilizzando
rows_table.get(row).findElements(By.tagName("td")); - Iteriamo attraverso ogni colonna e ogni riga e recuperiamo i valori.
Produzione :
















