Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
80 views
in Technique[技术] by (71.8m points)

python - Check if text exists on a page, but read the text from a variable (Selenium)

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!

question from:https://stackoverflow.com/questions/65860884/check-if-text-exists-on-a-page-but-read-the-text-from-a-variable-selenium

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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')]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...