2017-09-27 68 views
0

我想.click()在網頁上的彈出列表中的幾個元素,但繼續獲取StaleElementReferenceException當我嘗試move_to_elements。StaleElementReferenceException雖然試圖move_to_element(Python)

該代碼基於Feed中的多個可點擊元素。點擊後,這些元素會生成一個彈出框,其中包含更多可點擊的元素,我想訪問它們。

我訪問彈出框用下面的代碼,其中popupbox_links是與彈出框座標和鏈接的列表:

for coordinate in popupbox_links: 
    actions = ActionChains(driver) 
    actions.move_to_element(coordinate["Popupbox location"]).perform() 
    time.sleep(3) 
    popupboxpath = coordinate["Popupbox link"] 
    popupboxpath.click() 
    time.sleep(3) 

這工作得很好。但是在打開彈出框的時候,我想執行以下操作:

seemore = driver.find_element_by_link_text("See More") 
time.sleep(2) 
actions.move_to_element(seemore).perform() 
time.sleep(2) 
seemore.click() 
time.sleep(3) 
findbuttons = driver.find_elements_by_link_text("Button") 
time.sleep(2) 
print(findbutton) 
for button in findbuttons: 
    time.sleep(2) 
    actions.move_to_element(button).perform() 
    time.sleep(2) 
    button.click() 
    time.sleep(randint(1, 5)) 

麻煩開始於actions.move_to_element兩個「查看更多」和「按鈕」。即使print(findbutton)實際返回一個帶有內容的列表,其中包含我想要單擊的元素,但Selenium似乎無法對這些內容執行move_to_element。相反,它會拋出StaleElementReferenceException

爲了讓它更加混亂,該腳本似乎有時會奏效。雖然通常它只是崩潰。

關於如何解決這個問題的任何線索?非常感謝提前。

我使用Chrome WebDriver在Python 3.6上運行最新的Selenium。

回答

0

StaleElementReferenceException說明該元素是階段,因爲在創建webElement對象後,頁面中的內容發生了變化。在你的情況下,可能由於button.click()而發生。

最簡單的解決方案是每次創建新元素,而不是迭代循環中的元素。

以下更改可能會起作用。

findbuttons = driver.find_elements_by_link_text("Button") 
time.sleep(2) 
print(findbuttons) 
for i in range(len(findbuttons)): 
    time.sleep(2) 
    elem = driver.find_elements_by_link_text("Button")[i] 
    actions.move_to_element(elem).perform() 
    time.sleep(2) 
    elem.click() 
    time.sleep(randint(1, 5)) 
+0

感謝您的建議,稍後再嘗試。你將如何執行它首先: seemore = driver.find_element_by_link_text(「See More」) 因爲它不是一個迭代元素列表,但只是一個特定的元素。試圖移動它時,我仍然得到StaleElement。 –

+0

你必須找出你爲什麼得到它的根本原因,在你的問題是'點擊某個元素'。在這種情況下,它可能是任何東西。還有一個'Explicit Wait'來處理這個情況。 –