user14148145
user14148145

Reputation:

How to construct XPath from variables in Selenium?

Working :

driver.find_element_by_xpath("//span[text()='Feb 08, 2020 - Feb 08, 2021']").click()

Not Working :

driver.find_element_by_xpath("//span[text()=" + TimePeriodNoYear + TodaysYear[:-1] + "0" + " - " + TimePeriod + "]").click()

So, I understand that :

'Feb 08, 2020 - Feb 08, 2021'

is not equal to

Feb 08, 2020 - Feb 08, 2021

But then, How to pass variables inside the string included as argument for xpath ?

Upvotes: 1

Views: 129

Answers (2)

kjhughes
kjhughes

Reputation: 111521

Change

"//span[text()=" + TimePeriodNoYear + TodaysYear[:-1] + "0" + " - " + TimePeriod + "]"

to

"//span[text()='" + TimePeriodNoYear + TodaysYear[:-1] + "0" + " - " + TimePeriod + "']"
               ^                                                                     ^

Upvotes: 1

tbjorch
tbjorch

Reputation: 1758

You can use f-string formatting to add variables easily into a string.

E.g.

greeting = "Hello!"
presentation = "My name is John Doe "
my_string = f"{greeting} {presentation} and this is my formatted string!"

would produce and output as: Hello! My name is John Doe and this is my formatted string!

So basically in your case it would become something like this:

my_identifier = f"{TimePeriodNoYear}, {TodaysYear[:-1]}0 - {TimePeriod}"

Upvotes: 0

Related Questions