我想查询html表。 下面是我的代码,
browser.get("url.html")
# Wait 20 seconds for page to load
# have EC.visibility_of_element_located here
table_rows = browser.find_elements_by_xpath("//*[@id='table_id']/tbody/tr")
for row in table_rows:
print(row.find_element_by_xpath('./td[2]').text)
table_link = row.find_element_by_xpath('./td[1]/a')
table_link.click()
错误:
selenium.common.exceptions.StaleElementReferenceException:
我相信我迷失在页面上下文中。如何让此功能发挥作用。
selenium.common.exceptions.StaleElementReferenceException:
当元素未附加到页面时出现。当单击链接时,页面会刷新,元素不再附加到页面,它会变成 stale
。
要克服这个问题,您需要重新分配元素。 引发
WebDriverWait
() 并等待 visibility_of_all_elements_located
()
table_rows = WebDriverWait(browser,20).until(EC.visibility_of_all_elements_located((By.XPATH, "//*[@id='table_id']/tbody/tr")))
for row in range(len(table_rows)):
# re-assigned variable here
table_rows = WebDriverWait(browser,20).until(EC.visibility_of_all_elements_located((By.XPATH, "//*[@id='table_id']/tbody/tr")))
print(table_rows[row].find_element_by_xpath('./td[2]').text)
table_link = table_rows[row].find_element_by_xpath('./td[1]/a')
table_link.click()
#Perform details for the page
#
browser.back()
您需要导入这些库:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC