Home > OS >  How to get a value from a web table using Python Selenium?
How to get a value from a web table using Python Selenium?

Time:11-05

I can access to the page. I can go to the location of the table using Selenium xpath.

driver.find_elements('xpath', "/html/body/div/div/div[1]/div[2]/div[3]/div/div[4]/div[2]/div/div[2]/div/table/tbody/tr[2]/td[3]")

enter image description here

The question is how I can get the value inside the cell?

CodePudding user response:

You need to assign the result of your expression to a variable which will be an array of element objects. Since you are directly referencing a td element, the array will only have one element, which should be the value you are looking for. To get this value, use element[0].text.

element = driver.find_elements('xpath', "/html/body/div/div/div[1]/div[2]/div[3]/div/div[4]/div[2]/div/div[2]/div/table/tbody/tr[2]/td[3]")
print(element[0].text)

Here is a simple example of it working with a generic HTML table from w3schools:

...
driver.get("https://www.w3schools.com/html/html_tables.asp")
element = driver.find_elements('xpath', "/html/body/div[7]/div[1]/div[1]/div[3]/div/table/tbody/tr[3]/td[1]")
print(element[0].text)

Output: Centro comercial Moctezuma

  • Related