Any way to get the elements of a table as a matrix? Selenium + Python

0

I am getting the cells of a table this way with Selenium. What I'm getting is a list with the value of each cell.

def seleccionar_productos(driver):     
 rows = driver.find_elements_by_xpath("//table[@id='tabla']/tbody/tr") 

 cells = driver.find_elements_by_xpath("//table[@id='tabla']/tbody/tr/td")

 column_count = len(cells)/len(rows)     

 print ("filas=%s columnas=%s" % (row_count, column_count) )
 print( cells[0].get_attribute('innerHTML'))
 print( rows[0].get_attribute('innerHTML'))

I would like to be able to get the same thing but in the form of a matrix because it is easier to manage

The result of this is:

filas=10 columnas=14.0

The value of cells[0].get_attribute('innerHTML') gives me the value of the cell (Great).

But the value of rows[0].get_attribute('innerHTML') is intratable, something like that.

<td>Text1</td> <td>Text2</td> <td>Text3</td> <td>Text4</td> <td>Text4</td>....

The cells variable has values from 0 to 140

And I wish I could have it this way

cells[coll][row].get_attribute('innerHTML')

Where Coll will have values between 0 and 14, and row between 0 and 10

And if not some way to extract the values of the variable "rows".

Any questions?

    
asked by Iván Rodríguez 07.07.2018 в 22:25
source

1 answer

0

In the end I did this:

def crear_matriz(lista, n_filas, n_columnas):
 matriz = []
 count = 0
 for i in range(n_filas):
  matriz.append([])
  for j in range(n_columnas):
   matriz[i].append(lista[count])
   count+=1   
 return matriz




def seleccionar_productos(driver):     
 rows = driver.find_elements_by_xpath("//table[@id='tabla']/tbody/tr") 

 cells = driver.find_elements_by_xpath("//table[@id='tabla']/tbody/tr/td")

 column_count = len(cells)//len(rows)     

 print ("filas=%s columnas=%s" % (row_count, column_count) )

 matriz = crear_matriz(cells, row_count, column_count)

 for i in range(row_count):   
    print("%s %s %s %s %s %s %s" %
          (
          matriz[i][0].get_attribute('innerHTML'), 
          matriz[i][1].get_attribute('innerHTML'), 
          matriz[i][2].get_attribute('innerHTML'), 
          matriz[i][6].get_attribute('innerHTML'), 
          matriz[i][7].get_attribute('innerHTML'), 
          matriz[i][8].get_attribute('innerHTML'),
          matriz[i][9].get_attribute('innerHTML')
          )
          )

I do not know if it's the best way to do it but the truth is that I like it a lot more than the other one. If anyone knows how to get this using the Selenium tools directly, it would be great if I commented on it here.

    
answered by 08.07.2018 / 00:05
source