如何使用 webdriver python 获取与单选按钮对应的文本

Posted

技术标签:

【中文标题】如何使用 webdriver python 获取与单选按钮对应的文本【英文标题】:How do I get text corresponding to a radio button using webdriver python 【发布时间】:2012-08-24 23:27:20 【问题描述】:

我正在使用 webdriver 进行自动化,每个问题都有一些单选按钮,单选按钮旁边有一些文本,例如是/否。以下是我通过检查元素得到的代码

<label class="fs-508-label" for="editTemplate-editForm-content-flowTemplateFull-genericPage-_id162-page_0-profilerQuestionnaireBlock-_id167-page__1-questionnaire-_id169-0-questionRadio_com.taleo.functionalcomponent.prescreening.entity.question.PossibleAnswer__78620">   

<input name="editTemplate-editForm-content-flowTemplateFull-genericPage-_id162-page_0-profilerQuestionnaireBlock-_id167-page__1-questionnaire-_id169-0-questionRadio" id="editTemplate-editForm-content-flowTemplateFull-genericPage-_id162-page_0-profilerQuestionnaireBlock-_id167-page__1-questionnaire-_id169-0-questionRadio_com.taleo.functionalcomponent.prescreening.entity.question.PossibleAnswer__78620" value="com.taleo.functionalcomponent.prescreening.entity.question.PossibleAnswer__78620" type="radio" class="possibleanswers" onclick="onChoicePicked(this)"> 

No

</label>

你能帮我弄清楚吗? 我目前可以使用

获取单选按钮
element = browser.find_element_by_name(name got form above)

但是 element.text 并没有给我“不”而是空的,这让我感到困惑。我可能在这里遗漏了一些东西。

【问题讨论】:

【参考方案1】:

您的元素是空的,这是正确的行为。问题是,通过执行 browser.find("idblahblah") 您只需获得单选按钮元素本身,而不是文本,因为这是其他元素。文本本身是可以通过执行 driver.findElement(By.className("fs-508-label")) 找到的元素,但这不是最佳解决方案,因为类值往往会发生变化。 我建议将 html 改成这样:

<input id="true_radio_button" type="radio" name="bar"
value="bar_radio_true" checked="checked"/> 
<label id="whatever" for="true_radio_button">True</label>

这样您现在可以使用 ID 轻松找到单选按钮,然后找到相应的标签。可以通过检查“for”属性是否等于单选按钮 ID 来检查它是否正确 - label.getAttribute("for") 等于 radio_button_ID

编辑: 使用这个: driver.findElement(By.className("fs-508-label")) 应该可以正常工作

【讨论】:

我无法控制 html 页面。我不希望它被改变,当我尝试使用类名时,我收到错误说 webdriver 不支持复合名称。还有其他解决方案吗? 使用这个:driver.findElement(By.className("fs-508-label")) 应该可以正常工作吗?复合类错误意味着您尝试使用诸如 driver.findElements(By.className("first-classname second-classname")) 之类的东西来查找元素所以您应该只使用一个类来定位元素 感谢 driver.findElement(By.className("fs-508-label")) 正在工作。您能否编辑您的答案以包含您的评论。 完成了,但请记住我写的内容。并且在编写测试时,请尝试更加面向对象,就好像您是该应用程序的实际用户一样:)

以上是关于如何使用 webdriver python 获取与单选按钮对应的文本的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Python 中使用 Selenium WebDriver 获取文本

如何在python中使用Selenium WebDriver获取整个网页源[重复]

如何使用 Selenium WebDriver 和 python 获取 Web 元素的颜色?

从python中的Selenium Webdriver实例获取文本[重复]

如何使用 Selenium WebDriver 获取 Inspect Element 代码

与Python Scrapy中的Selenium WebDriver并发