0

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

    2 Answers 2

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

    Just use format.

      1

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

        Start asking to get answers

        Find the answer to your question by asking.

        Ask question

        Explore related questions

        See similar questions with these tags.