我宁愿不使用xpath,除非它确实是唯一的方法。 这是我正在玩的简单复选框:w3schools.checkbox
我想查看“我有一辆自行车”。我尝试在find_element_by_name
上调用self.driver
方法但是没有成功,这是我使用xpaths的悲惨尝试:
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']`
我做错了什么?
答案 0 :(得分:1)
位于input
内的目标iframe
字段。要处理复选框,您必须先切换到iframe
:
self.driver.switch_to.frame("iframeResult")
self.driver.find_element_by_xpath(bike_xpath)
它也应该由name
:
self.driver.find_element_by_name("vehicle")
但请注意,名称"vehicle"
适用于两个复选框
您也可能需要使用
self.driver.switch_to.default_content()
从iframe