代码行 11,12 为何定位不到元素
1 #-*-coding:UTF-8 -*- 2 __author__ = 'ljw' 3 from selenium import webdriver 4 from selenium.webdriver.common.by import By 5 import time 6 driver=webdriver.Firefox() 7 driver.get("http://www.taobao.com") 8 driver.maximize_window() 9 driver.find_element_by_partial_link_text("高级").click() 10 time.sleep(10) 11 le1=len(driver.find_elements_by_css_selector("a.fake-checkbox.field")) 12 le2=len(driver.find_elements(By.CSS_SELECTOR,"a.fake-checkbox.field")) 13 print le1 14 print le2 15 driver.quit()
找到原因了,原来并不是定位方式错误的原因,driver 打开另一个窗口时,当前页面仍是前面那个。
1 __author__ = 'ljw' 2 from selenium import webdriver 3 from selenium.webdriver.common.by import By 4 import time 5 driver=webdriver.Firefox() 6 driver.get("http://www.taobao.com") 7 driver.maximize_window() 8 windows1=driver.current_window_handle 9 driver.find_element_by_partial_link_text("高级").click() 10 windows=driver.window_handles 11 for handle in windows: 12 if handle != windows1: 13 driver.switch_to_window(handle) 14 break 15 checks=driver.find_elements_by_css_selector("a.fake-checkbox.field") 16 for check in checks: 17 check.click() 18 checks.pop().click() 19 time.sleep(10) 20 driver.quit()
第9行click后 跳转到下一窗体 应该先找到下一窗体再进行元素查找