本文介绍了在Python中使用Selenium单击/选择单选按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从3个按钮的列表中进行选择,但是找不到选择它们的方法.下面是我正在使用的HTML.
I am trying to select from a list of 3 buttons, but can't find a way to select them. Below is the HTML I am working with.
<input name="pollQuestion" type="radio" value="SRF">
<font face="arial,sans-serif" size="-1">ChoiceOne</font><br />
<input name="pollQuestion" type="radio" value="COM">
<font face="arial,sans-serif" size="-1">ChoiceTwo</font><br />
<input name="pollQuestion" type="radio" value="MOT">
<font face="arial,sans-serif" size="-1">ChoiceThree</font>
我可以使用以下代码找到它:
I can find it by using the following code:
for i in browser.find_elements_by_xpath("//*[@type='radio']"):
print i.get_attribute("value")
此输出:SRF,COM,MOT
This outputs: SRF,COM,MOT
但是我想选择ChoiceOne. (单击它)我该怎么做?
But I would like to select ChoiceOne. (To click it) How do I do this?
推荐答案
使用CSS选择器或XPath直接通过value
属性进行选择,然后单击它.
Use CSS Selector or XPath to select by value
attribute directly, then click it.
browser.find_element_by_css_selector("input[type='radio'][value='SRF']").click()
# browser.find_element_by_xpath(".//input[@type='radio' and @value='SRF']").click()
更正(但是OP应该学习如何在文档中查找)
Corrections (but OP should learn how to look up in documentation)
- 在Python绑定中,
find_elements_by_css
不存在,称为find_elements_by_css_selector
.一个人应该能够查看异常消息并回顾文档在此并找出原因. - 是否注意到
find_element_by_css_selector
和find_elements_by_css_selector
之间的区别?第一个找到第一个匹配的元素,第二个找到一个列表,因此您需要使用[0]进行索引. 此处是API文档.之所以使用后者,是因为我复制了您的代码,但我不应该这样做.
- In Python binding,
find_elements_by_css
doesn't exist, it's calledfind_elements_by_css_selector
. One should be able to look at the exception message and look back into documentation here and figure out why. - Notice the difference between
find_element_by_css_selector
andfind_elements_by_css_selector
? The first one finds the first matching element, the second one finds a list, so you need to use [0] to index. Here is the API documentation. The reason why I use the latter, is because I copied your code, which I shouldn't.
这篇关于在Python中使用Selenium单击/选择单选按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!