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

2024-06-16 14:45:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我宁愿避免使用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']`

我做错了什么?在


Tags: 方法fromimportselfinputbydriverselenium
1条回答
网友
1楼 · 发布于 2024-06-16 14:45:41

位于iframe内的目标input字段。要处理复选框,必须先切换到iframe

self.driver.switch_to.frame("iframeResult")
self.driver.find_element_by_xpath(bike_xpath)

它也应该可以通过name访问:

^{pr2}$

但请注意,名称"vehicle"应用于这两个复选框

您可能还需要使用

self.driver.switch_to.default_content()

iframe返回

相关问题 更多 >