Python selenium webdriver无法找到元素

时间:2017-04-23 11:08:57

标签: python selenium-webdriver

我的python Selenium程序找不到我认为web元素所在的框架。如果我做错了,请告诉我。谢谢。

# switch back to main window
driver.switch_to.window(main_window_handle)
time.sleep(5)
driver.switch_to.frame("header");
driver.find_element_by_id("a_1").click()
time.sleep(10)

# switch back to main window
driver.switch_to.window(main_window_handle)
time.sleep(5)
driver.switch_to.frame("contents");               ***<----- failed here***
time.sleep(5)
driver.switch_to.window("itreecontrol");
time.sleep(5)
# Click on desired item
driver.find_element_by_xpath("//div/a/span/span/span").click()

enter image description here

===============================

其他问题:在弹出窗口中找不到元素

# switch back to main window
driver.switch_to.window(main_window_handle)
time.sleep(5)
driver.switch_to.frame("header");
driver.find_element_by_id("a_1").click()
time.sleep(10)

# Go to correct frame first
driver.switch_to.default_content()
driver.switch_to.frame("contents");
driver.switch_to.frame(driver.find_element_by_tag_name("iframe"));
time.sleep(5)
# Click on plus icon to pop up a window
driver.find_element_by_xpath("//div/a/span/span/span").click()

# Enter your info in this text-field element in the popped-up window
# (failed to find "unitName-inputEl" here)
driver.find_element_by_id("unitName-inputEl").clear()       <--- failed here

更新了代码-1

# switch back to main window
driver.switch_to.window(main_window_handle)   
# Click on 'Firewall' panel
time.sleep(5)
driver.switch_to.frame("header");
driver.find_element_by_id("a_1").click()
time.sleep(10)

# switch to default content
driver.switch_to.default_content()
# Go to the correct frame first
driver.switch_to.frame("contents");
driver.switch_to.frame("itreecontrol");
time.sleep(5)
# Click on plus-box icon to display pop-up
driver.find_element_by_xpath("//div/a/span/span/span").click()

driver.find_element_by_id("unitName-inputEl").clear()
#driver.find_element_by_id("unitName-inputEl").send_keys("tz400")
wait(driver, 10).until(EC.element_to_be_clickable((By.ID, "unitName-inputEl"))).send_keys('tz400')

enter image description here

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:1)

切换到<iframe id="header">后,您需要切换回默认内容才能切换到<iframe id="contents">

尝试:

driver.switch_to.frame("header");
driver.find_element_by_id("a_1").click()
time.sleep(10)

driver.switch_to.default_content()
time.sleep(5)
driver.switch_to.frame("contents")
driver.switch_to.frame("itreecontrol")

要处理input字段,您可以尝试使用ExplicitWait,如下所示:

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

wait(driver, 10).until(EC.element_to_be_clickable((By.ID, "unitName-inputEl"))).send_keys('tz4‌​00')