python+selenium2自動化---定位元素報錯element click intercepted


一、通過執行js腳本觸發點擊事件

頁面元素結構如下圖所示:

通過如下方式獲取該元素后直接點擊會報錯:

selenium.common.exceptions.WebDriverException: Message: element click intercepted: Element <span role="img" id="btn_layer_title_options" tabindex="-1" class="anticon i-more ant-dropdown-trigger">...</span> is not clickable at point (467, 22). Other element would receive the click: <svg width="1em" height="1em" fill="currentColor" aria-hidden="true" focusable="false" class="">...</svg>

more_btn = WebDriverWait(self.driver,20,0.5).until( EC.visibility_of_element_located((By.ID,'btn_layer_title_options'))
more_btn.click()

解決方法:通過執行js腳本點擊該元素

more_btn = WebDriverWait(self.driver,20,0.5).until(
            EC.visibility_of_element_located((By.ID,'btn_layer_title_options')
driver.execute_script("arguments[0].click();", more_btn)

二、通過pyautogui庫操作

pyautogui是一個圖形用戶界面自動化工具,通過屏幕x,y坐標系統來確定目標位置,控制鼠標和鍵盤發送虛擬擊鍵和鼠標點擊,完成點擊按鈕、填寫表單等操作

1、安裝

https://pypi.org/project/PyAutoGUI下載PyAutoGUI-0.9.38.tar.gz,解壓后,進入解壓目錄執行python setup.py install

2、常用方法

#確定鼠標當前位置
pyautogui.position() #點擊
pyautogui.moveTo() pyautogui.mouseDown() pyautogui.mouseUp() pyautogui.click() pyautogui.doubleClick() pyautogui.rightClick() pyautogui.middleClick() #拖動
pyautogui.dragTo() #控制鍵盤
pyautogui.typewrite()

3、實例

下圖中同意協議框,按理說通過id可以定位到,然后進行點擊勾選,但實際上是會報錯,不支持點擊:

from selenium import webdriver from time import sleep class TestCase(): def __init__(self): self.driver = webdriver.Chrome() self.driver.maximize_window() self.driver.get('http://www.jpress.io/user/register') def test01(self): self.driver.find_element_by_id('agree').click() sleep(3) self.driver.quit() if __name__ == '__main__': TestCase().test01()

上述代碼報錯如下:

 下面通過pyautogui工具來實現點擊該元素

from selenium import webdriver from time import sleep class TestCase(): def __init__(self): self.driver = webdriver.Chrome() self.driver.maximize_window() self.driver.get('http://www.jpress.io/user/register') def test01(self): ele = self.driver.find_element_by_id('agree') rect = ele.rect #以字典方式返回元素的大小和坐標
        #rect = {'height': 24, 'width': 18, 'x': 591.6000366210938, 'y': 563.9750366210938}
 pyautogui.FAILSAFE = False #將鼠標移動到指定位置,要調試得到對應的偏移量
        pyautogui.moveTo(rect['x']+160,rect['y']+300) #點擊
 pyautogui.click() sleep(3) self.driver.quit() if __name__ == '__main__': TestCase().test01()

也可以通過如下方法點擊該元素

ele = self.driver.find_element_by_id('agree') ActionChains(self.driver).move_to_element(ele).click().perform()

 

 


免責聲明!

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



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