2016-08-02 155 views
0

我在python中創建了一個腳本,該腳本通過一個帶有三列的表。我創建了一個列表,第一列中的每個鏈接都插入到列表中。然後我循環。當循環時,我點擊鏈接,打印一條語句以確保它實際上點擊鏈接,然後轉到上一頁,以便可以單擊下一個鏈接。我一直得到的錯誤是,我的循環先通過前兩個鏈接,然後當循環第三次調用鏈接[page] .click()時,我得到一個StaleElementReferenceException。我無法發佈html,因爲該網站是保密的。網絡抓取鏈接表

from selenium import webdriver 
    from selenium.webdriver.common.keys import Keys 
    from selenium.webdriver.common.by import By 
    from selenium.webdriver.support.ui import Select 
    import traceback 


    # starting chrome browser 
    chrome_path = r"C:\Users\guaddavi\Downloads\chromedriver_win32 extract\chromedriver.exe" 
    browser = webdriver.Chrome(chrome_path) 


    #linking to page 
    browser.get('link to page with table ') 


    #find table of ETL Extracts 
    table_id = browser.find_element_by_id('sortable_table_id_0') 
    #print('found table') 

    #get all the rows of the table containing the links 
    rows = table_id.find_elements_by_tag_name('tr') 

    #remove the first row that has the header 
    del rows[0] 
    current = 0 
    links = [] * len(rows) 

    for row in rows: 
    col = row.find_elements_by_tag_name('td')[0] 
    links.append(col) 
    current +=1 

    page = 0 
    while(page <= len(rows)): 
     links[page].click() 
     print('clicked link' + " " + str(page)) 
     page += 1 
     browser.back()  

回答

1

我不知道你已經看到了官方的硒文檔:

一個過時的元素引用異常是在兩種情況之一拋出,首先是超過第二常見的有: 元素已被完全刪除。 元素不再附加到DOM。

在你的情況,我認爲你有第二個問題。每次點擊並返回循環時,DOM都在改變。請檢查一下。