Selenium 按钮选择器并单击

Selenium Button Selector and Click

我想在 Python 上使用 Selenium 自动重启我的路由器。一切正常,除了最后一步,即找到重启按钮并单击它!

我尝试通过 (id, css_selector, name, value, xpath) 定位它,但似乎没有任何效果。

这是我的代码:

driver = webdriver.Firefox()
driver.get('http://192.168.100.1')

english = driver.find_element_by_id("English")
english.click()

usr = "username"
pwd = "password"

usrname_box = driver.find_element_by_id("txt_Username")
usrname_box.send_keys(usr)

pwd_box = driver.find_element_by_id("txt_Password")
pwd_box.send_keys(pwd)

submit_ = driver.find_element_by_id("button")
submit_.click()
sleep(1)


resetit = driver.find_element_by_name("maindiv_reset")
resetit.click()
sleep(1)

# This is the one I want to locate
reboot = driver.find_element_by_xpath("//input[@id='btnReboot']")
reboot.click()

这是目标按钮的 HTML 代码:

<input class="ApplyButtoncss buttonwidth_150px" name="btnReboot" id="btnReboot" type="button" onclick="Reboot()" bindtext="s0603" value="Restart">

尝试任何操作时,出现错误:

NoSuchElementException: Message: Unable to locate element: (WHATEVER I TRY)

HTML 页面的屏幕截图:

提前感谢大家的帮助。

你这个:

reboot = driver.find_element_by_name("btnReboot")
reboot.click()

作为最后的解决方案,您可以告诉 Python 单击重新启动按钮,假设您可以在屏幕上找到像素 (X, Y) 坐标,并且假设当 [=14] 时 Firefox 浏览器不会移动=] 脚本。参见 here

所需的元素是 JavaScript enabled element so to locate and click() on the element you have to induce WebDriverWait for the element to be clickable and you can use either of the following :

  • 使用CSS_SELECTOR:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input.ApplyButtoncss.buttonwidth_150px#btnReboot[value='Restart']"))).click()
    
  • 使用XPATH:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@class='ApplyButtoncss buttonwidth_150px' and @id='btnReboot'][@value='Restart']"))).click()
    
  • 注意:您必须添加以下导入:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    

由于目标按钮包含在iframe中,我使用以下方法解决问题:

iframe = driver.find_element_by_id("frameContent")
driver.switch_to.frame(iframe)
driver.find_element_by_id('btnReboot').click()
alert = driver.switch_to_alert()
alert.accept()

非常感谢所有试图提供帮助的人,尤其是 DebanjanB