简体   繁体   English

如何在 selenium 中查找包含使用 python 的文本的 web 元素

[英]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.

相关问题 Selenium function 在 Python 中查找包含部分文本的页面和元素 - Selenium function in Python to find on page and element that contains partial text Python Selenium按链接文本查找元素包含带通配符或正则表达式的字符串 - Python Selenium find element by link text contains a string with wildcard or regex 如何在 python 中使用 Selenium 查找所有元素和文本 - How to find all element and text by using Selenium in python 如何使用 Selenium Python 通过链接文本查找元素 - How to Find Element by Link Text using Selenium Python 使用Selenium和Python查找具有特定文本的元素 - Find element with certain text using Selenium with Python If Statements with Selenium using find element by xpath(包含文本) - If Statements with Selenium using find element by xpath (contains text) 如何在 Selenium WebDriver (Python) 中找到包含特定文本的元素? - How do I find an element that contains specific text in Selenium WebDriver (Python)? Selenium Python:如何 web 刮取元素文本 - Selenium Python: How to web scrape the element text Selenium Python:find_element_by_css_selector()使用:contains() - Selenium Python: find_element_by_css_selector() using :contains() Python Selenium 如何找到带有变化文本的元素 - Python Selenium how to find element with changing text
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM