八、selenium定位元素后,click不生效的問題。


實現自動化登錄微雲賬號。

 問題分析

 

firefox_driver = webdriver.Firefox()
    firefox_driver.get("https://www.weiyun.com/")
    firefox_driver.implicitly_wait(10)
 # 登錄賬號
    firefox_driver.switch_to.frame("qq_login_iframe")
    firefox_driver.find_element_by_css_selector("#switcher_plogin").click()
    # print(s.text)
    input_name = firefox_driver.find_element_by_css_selector("#u")
    input_name.clear()
    input_name.send_keys("***")
    input_password = firefox_driver.find_element_by_css_selector("#p")
    input_password.clear()
    input_password.send_keys("****")
    firefox_driver.find_element_by_css_selector("#login_button").click()
    time.sleep(3)
    firefox_driver.quit()

上述代碼執行時,並沒有點擊[賬號密碼登錄]的效果,並且報錯

selenium.common.exceptions.ElementNotInteractableException: Message: element not interactable

分析源碼可知,賬號輸入所在的div默認是不可見的,手動點擊賬號可使其可見。但是手動點擊[賬號與密碼登錄]不生效。

如何定位呢?

1.先排除是否找到了需要click的元素

a.確實元素是否在frame,在的話,是否以成功切換了frame。

輸出window_handles可知,雖然內嵌了frame,但是實際上還是在一個window上,那么不能由此判斷是否已成功切換了frame。試了下switch_to.frame不存在的frame,報錯NoSuchFrameException。那么我認為我這里切換到frame是成功了的。盡管這里似乎跨域了,但是好像並不影響。

關於跨域https://blog.csdn.net/a250758092/article/details/84026235

b.這里find[賬號與密碼登錄]時並沒有拋異常,並且元素是可見的。其實可以認為元素已經找到了,但是為什么click()還是無效果呢?試下time.sleep(),發現也是也不行。

c.試下其他點擊

  js:

firefox_driver.execute_script("document.getElementById('switcher_plogin').click()")

如果也是不行,試下ActionChains

2.是否存在頁面刷新,導致元素失效,或者切換了其他窗口句柄呢?

成功的代碼實現

firefox_driver = webdriver.Firefox()
    firefox_driver.get("https://www.weiyun.com/")
    firefox_driver.implicitly_wait(10)
# 登錄賬號
    firefox_driver.switch_to.frame("qq_login_iframe")
    firefox_driver.execute_script("document.getElementById('switcher_plogin').click()")
    time.sleep(2)
    input_name = firefox_driver.find_element_by_css_selector("#u")
    input_name.clear()
    input_name.send_keys("***")
    input_password = firefox_driver.find_element_by_css_selector("#p")
    input_password.clear()
    input_password.send_keys("****")
    firefox_driver.find_element_by_css_selector("#login_button").click()
    time.sleep(3)
    firefox_driver.quit()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM