如何在Python3中使用selenium选中复选框

如何在Python3中使用selenium选中复选框,python,selenium,xpath,Python,Selenium,Xpath,我宁愿避免使用XPath,除非这确实是唯一的方法。 下面是我正在使用的简单复选框: 我想检查一下“我有一辆自行车”。我尝试在self.driver上调用find\u element\u by\u name方法,但没有成功,下面是我使用XPath的痛苦尝试: from selenium import webdriver from selenium.common.exceptions import NoSuchElementException class CheckBox: def __i

我宁愿避免使用XPath,除非这确实是唯一的方法。 下面是我正在使用的简单复选框:

我想检查一下“我有一辆自行车”。我尝试在
self.driver
上调用
find\u element\u by\u name
方法,但没有成功,下面是我使用XPath的痛苦尝试:

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException

class CheckBox:
    def __init__(self):
        self.url = 'https://www.w3schools.com/tags/tryit.asp?filename=tryhtml_input_checked'
        self.driver = webdriver.Firefox()
        self.driver.get(self.url)

    def check_I_have_a_bike(self):
        bike_xpath = ".//input[@value='Bike']" # seems pretty straightforward and simple
        try:
            self.driver.find_element_by_xpath(bike_xpath).click()
        except NoSuchElementException as e:
            print('Error: {error_message}'.format(error_message=e))

checker = CheckBox()
checker.check_I_have_a_bike()

`Error: Unable to locate element: .//input[@value='Bike']`

我做错了什么?

目标
输入
字段位于
iframe
中。要处理复选框,必须首先切换到
iframe

self.driver.switch_to.frame("iframeResult")
self.driver.find_element_by_xpath(bike_xpath)
也可以通过
名称
访问:

self.driver.find_element_by_name("vehicle")
但请注意,名称
“vehicle”
应用于两个复选框

此外,您可能需要使用

self.driver.switch_to.default_content()

要从
iframe

Hmmm切换回来,它起作用了。好像我没有玩足够多的XPath来解决我自己的问题。但是如果不先切换到iframe,就没有其他方法了,对吗?
iframe
是另一个
HTML
文档,它嵌入到主文档中。因此,每次需要处理适当的元素时,都应该在main
DOM
iframe
DOM
之间切换,明白了吗。多谢各位!