Lucky1234
Lucky1234

Reputation: 125

How to find a web element in selenium that contains a text using python

I want to find a web element that contains text 'My' .But the text is stored in a variable named msg

msg = "My"

How do I use the variable in the xpath and find the web element . I also want to click the element

below code works if I give the text directly in the xpath . But i want to use the variable msg to generalize

driver.find_elements_by_xpath("//*[contains(text(), 'My')]")

Upvotes: 0

Views: 291

Answers (2)

Vova
Vova

Reputation: 3537

You can use text equals as well:

driver.find_element_by_xpath("//*[text()='{}']".format("you_text"))

but I agree, contains is more flexible:

driver.find_element_by_xpath("//*[contains(text(),'{}')]".format("you_text"))

Upvotes: 1

Arundeep Chohan
Arundeep Chohan

Reputation: 9969

driver.find_element_by_xpath("//*[contains(text(), '{}')]".format(msg))

Just use format.

Upvotes: 1

Related Questions