python - 如何在Python3中使用selenium检查复选框

标签 python selenium xpath

我宁愿避免使用 xpath,除非它确实是唯一的方法。 这是我正在使用的简单复选框:w3schools.checkbox

我想查看“我有一辆自行车”。我尝试在 self.driver 上调用 find_element_by_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 切换回来

关于python - 如何在Python3中使用selenium检查复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42721690/

相关文章:

python - 从 python 列表中进行窗口选择

python - 格式化 Django 中作为字符串提供的日期时间

java - 如何减少 Selenium 中 NoSuchElementException 的等待时间?

docker - 升级到 ChromeDriver v80 和 Chrome v80 后,Chrome 无法在使用 Selenium 的 docker 容器中启动

python - 如何使用selenium在python的特定文本后定位输入元素

python - 在 Python 中并行对共享数据执行大量计算

selenium - 方法executeScript(selenium web driver)不能定义全局变量供以后使用?

ruby - REXML 无法从属性中进行选择。错误或不正确的 XPath?

c# - 仅当子元素具有特定数量的元素时才选择父元素

python - 使用 Binascii Hexlify 输入