I am trying to pass a variable to find_element_by_xpath
.
When I use the following statement it works ok:
driver.find_element_by_xpath("//tbody/tr/td[contains(.,'searchtext')]/following::td[1]").text
But when I try to pass the search text as a variable like this I get an error:
myvariable = 'searchtext'
driver.find_element_by_xpath("//tbody/tr/td[contains(.,'myvariable')]/following::td[1]").text
It's the same with this:
myvariable = 'searchtext'
driver.find_element_by_xpath("//tbody/tr/td[contains(.,(myvariable)')]/following::td[1]").text
What am I doing wrong?
CodePudding user response:
That's the wrong parsing you've done. Use f-string, read more about f-Strings: A New and Improved Way to Format Strings in Python
so instead of
myvariable = 'searchtext'
driver.find_element_by_xpath("//tbody/tr/td[contains(.,'myvariable')]/following::td[1]").text
do this :
myvariable = 'searchtext'
driver.find_element_by_xpath(f"//tbody/tr/td[contains(.,'{myvariable}')]/following::td[1]").text
CodePudding user response:
You are writing the myvariable as a string, and not passing in the variable.
Instead use .format
like this:
myvariable = 'searchtext'
driver.find_element_by_xpath("//tbody/tr/td[contains(.,{})]/following::td[1]").text.format(myvariable)
CodePudding user response:
You cannot fill the variable this way. Better use str.format :
myvariable = 'searchtext'
driver.find_element_by_xpath( str.format("//tbody/tr/td[contains(.,'{}')]/following::td[1]"),myvariable)).text
Other way is to can at strings :
myvariable = 'searchtext'
driver.find_element_by_xpath("//tbody/tr/td[contains(.,' ” myvariable ”’)]/following::td[1]").text