-1

I am trying to find a matching text on a page with Selenium, but I am not sure how to make it read an input string from a variable. For example:

video_title = 'Michael Jackson - Thriller'
driver.find_elements_by_xpath("//*[contains(text(), video_title)]")

The code above does not give me good results, as it probably searches literary for "video_title", and not the string inside. I omited the standard quotes arround video_title in the code above, in hopes of Selenium looking at it as a variable, but it doesn't seem to work.

Is this possible to do? With Selenium, or some other way? Thanks!

keen
  • 3
  • 2
  • Might be similar to this question. https://stackoverflow.com/questions/48139676/how-to-get-the-value-of-an-element-in-python-selenium/48139708 – Noob Jan 23 '21 at 15:24
  • If you won't know if it possible to run this code and you will see the result – dimay Jan 23 '21 at 15:26
  • Yeah, sorry, forgot to mention that I am expetimetning with the code, but it does not work I want it to. It searches for "video_title" literary, and not the string inside. – keen Jan 23 '21 at 15:31
  • 1
    Search for "python string formatting" for examples of how to construct a string value from a variable. – John Gordon Jan 23 '21 at 15:46

1 Answers1

0

You need to pass the video title as a variable instead of as text, as displayed in the code below:

video_title = 'Michael Jackson - Thriller'
driver.find_elements_by_xpath("//*[contains(text(), '" + video_title + "')]")

Note the extra single quote around video_title, required because it's a string. At runtime this will result in the following XPath expression:

//*[contains(text(), 'Michael Jackson - Thriller')]
Bouke
  • 1,531
  • 1
  • 12
  • 21