1

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 ?

2
  • 4
    Just add single quotes to your string concatenation to make it the same Commented Feb 8, 2021 at 14:37
  • 1
    @h4z3 could you then pls share an answer ? I'm quite confuse at this moment with what you are saying. Thank you very much. Commented Feb 8, 2021 at 14:39

2 Answers 2

1

Change

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

to

"//span[text()='" + TimePeriodNoYear + TodaysYear[:-1] + "0" + " - " + TimePeriod + "']"
               ^                                                                     ^
Sign up to request clarification or add additional context in comments.

5 Comments

But beware that constructing XPath expressions by string concatenation (a) is inefficient, and (b) exposes you to injection attacks. If your XPath API allows setting values of parameters in the XPath expression, that's a far better mechanism - but sadly not all APIs allow this (and I don't know whether Selenium does).
@Michael Kay Thank you for your comment, I was going to put this answer as accepted. Because yes It's working well and a good answer. But what you are saying it's true so could you please share with us an answer which will not be exposed to different risks ?
@MichaelKay: Right, perf and injection risk are worth noting in general but probably less of a worry in the typical Selenium testing or scraping applications such as here where the immediate problem was due to the missing ' characters. See also How to pass variable parameter into XPath expression?
One of the shortest answer I've ever seen from @kjhughes
@DebanjanB: Haha, I hope I don't usually drone on like Polonius: ...Therefore, since brevity is the soul of wit...
0

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}"

1 Comment

Your answer is right. I upvoted. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.