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 ?

kjhughes
  • 106,133
  • 27
  • 181
  • 240
LuckyFr
  • 401
  • 1
  • 5
  • 19
  • 4
    Just add single quotes to your string concatenation to make it the same – h4z3 Feb 08 '21 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. – LuckyFr Feb 08 '21 at 14:39

2 Answers2

2

Change

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

to

"//span[text()='" + TimePeriodNoYear + TodaysYear[:-1] + "0" + " - " + TimePeriod + "']"
               ^                                                                     ^
kjhughes
  • 106,133
  • 27
  • 181
  • 240
  • 1
    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 Feb 08 '21 at 16:32
  • 1
    @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 ? – LuckyFr Feb 08 '21 at 16:48
  • 2
    @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?](https://stackoverflow.com/q/30352671/290085) – kjhughes Feb 08 '21 at 18:02
  • One of the shortest answer I've ever seen from @kjhughes – undetected Selenium Feb 08 '21 at 21:33
  • 1
    @DebanjanB: Haha, I hope I don't usually drone on like Polonius: *...Therefore, since brevity is the soul of wit...* – kjhughes Feb 08 '21 at 22:28
1

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}"
tbjorch
  • 1,544
  • 1
  • 8
  • 21