我想查询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("//*[,python,selenium,selenium-webdriver"/>
	














首页 > 解决方案 > Selenium - Python如何在循环内一一单击行元素

我想查询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("//*[

问题描述

我想查询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:

我相信我迷失在页面上下文中。如何使此功能正常工作。

  1. 我的意思是转到一页。
  2. 对于每个表 tr
  3. 读td
  4. 点击第一个 td
  5. 从第 (4) 页抓取一些信息
  6. 回去
  7. 再次循环继续

您将 baseURL 与 axios Post 附加到哪里?我想你忘了附加那个?

标签: pythonseleniumselenium-webdriver

解决方案


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
     

推荐阅读