[英]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我想找到一个包含文本“My”的 web 元素。但文本存储在名为 msg 的变量中
msg = "My"味精=“我的”
How do I use the variable in the xpath and find the web element.如何使用 xpath 中的变量并找到 web 元素。 I also want to click the element
我也想点击元素
below code works if I give the text directly in the xpath.如果我直接在 xpath 中给出文本,则下面的代码有效。 But i want to use the variable msg to generalize
但我想使用变量 msg 来概括
driver.find_elements_by_xpath("//*[contains(text(), 'My')]")
driver.find_element_by_xpath("//*[contains(text(), '{}')]".format(msg))
Just use format.只需使用格式。
You can use text equals as well:您也可以使用文本等于:
driver.find_element_by_xpath("//*[text()='{}']".format("you_text"))
but I agree, contains is more flexible:但我同意, contains 更灵活:
driver.find_element_by_xpath("//*[contains(text(),'{}')]".format("you_text"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.