如何通过 Selenium 中的文本(Python)查找带有 Selenium 的按钮?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49906237/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to find button with Selenium by its text inside (Python)?
提问by sprogissd
I have the following three buttons that I can't figure out how to grab the text that is inside of them (e.g Outliers). I tried browser.find_element_by_link_text("Outliers").click()
, but got "Unable to locate element" error. How can I do it?
我有以下三个按钮,我不知道如何获取其中的文本(例如异常值)。我试过了browser.find_element_by_link_text("Outliers").click()
,但出现“无法定位元素”错误。我该怎么做?
回答by jmunsch
Another example XPath:
另一个例子 XPath:
browser.find_element_by_xpath('//button[text()="Outliers"]')
回答by Grasshopper
Try this XPath:
试试这个 XPath:
"//button[@class='three-state-item btn btn-default'][.='Outliers']"
.
"//button[@class='three-state-item btn btn-default'][.='Outliers']"
.
回答by Pritam Maske
There are two ways :
有两种方法:
- By using text()method -
browser.find_element_by_xpath('//button[text()="Outliers"]') - By using normalize-space()method - browser.find_element_by_xpath('//button[normalize-space()="Outliers"]')
- 通过使用text()方法 -
browser.find_element_by_xpath('//button[text()="Outliers"]') - 通过使用normalize-space()方法 - browser.find_element_by_xpath('//button[normalize-space()="Outliers"]')
Note :It is always better to use normalize-space()method as it will work even if there are spaces presentat the start of your text or at the end of text, because normalize-space() method trim the left and rightside spaces
注:它始终是更好地使用正常化空间()方法,因为它会工作,即使有存在的空间处文本的末尾文本或开始,因为正常化空间()方法修剪左右侧空间