如何通过 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 19:17:12  来源:igfitidea点击:

How to find button with Selenium by its text inside (Python)?

pythonseleniumselenium-webdriver

提问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(),但出现“无法定位元素”错误。我该怎么做?

enter image description here

在此处输入图片说明

回答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 :

有两种方法:

  1. By using text()method -
    browser.find_element_by_xpath('//button[text()="Outliers"]')
  2. By using normalize-space()method - browser.find_element_by_xpath('//button[normalize-space()="Outliers"]')
  1. 通过使用text()方法 -
    browser.find_element_by_xpath('//button[text()="Outliers"]')
  2. 通过使用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

注:它始终是更好地使用正常化空间()方法,因为它会工作,即使有存在的空间处文本的末尾文本或开始,因为正常化空间()方法修剪左右侧空间