Home > database >  I want to use a variable to specify rows <tr> in a table
I want to use a variable to specify rows <tr> in a table

Time:11-12

I have a table and wish to find specific rows by inserting a variable such as /tr[i]/ where i is the row I'm after.

If I hardwire the element in my code, it works fine:

    driver.find_element_by_xpath("//tbody[@class='sample']/tr[2]/td[2]/button/img").get_attribute("src")

I get the "src" attribute as expected.

But if I use a variable to examine the row of interest, I get an error:

i = 2
driver.find_element_by_xpath("//tbody[@class='sample']/tr[i]/td[2]/button/img").get_attribute("src")

returns error: selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//tbody[@class='sample']/tr[i]/td[2]/button/img"}

I code very rarely but I know I've used variables for /tr[i]/ before. What am I doing wrong?

CodePudding user response:

You want to use the formatting f-string and curly braces to use the value i

i = 2
driver.find_element_by_xpath(f"//tbody[@class='sample']/tr[{i}]/td[2]/button/img").get_attribute("src")
  • Related