我宁愿避免使用 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/