我有一个包含 16 行 5 列 HTML 表格的页面。 我有一种方法可以循环遍历表格并打印出单元格值。 我收到以下错误:
raise exception_class(message, screen, stacktrace)
StaleElementReferenceException: Message: Element is no longer valid
错误发生在这一行:
col_name = row.find_elements(By.TAG_NAME, "td")[1] # This is the Name column
我的方法代码是:
def get_variables_col_values(self):
try:
table_id = self.driver.find_element(By.ID, 'data_configuration_variables_ct_fields_body1')
#time.sleep(10)
rows = table_id.find_elements(By.TAG_NAME, "tr")
print "Rows length"
print len(rows)
for row in rows:
# Get the columns
print "cols length"
print len(row.find_elements(By.TAG_NAME, "td"))
col_name = row.find_elements(By.TAG_NAME, "td")[1] # This is the Name column print "col_name.text = "
print col_name.text
except NoSuchElementException, e:
return False
我是否因为 dom 已更新、更改而导致元素不再有效? 该表尚未完成加载? 请问我该如何解决这个问题? 我需要等待页面完全加载完成吗?
我应该使用以下 WebdriverWait 代码来等待页面加载完成吗?
WebDriverWait(self.driver, 10).until(lambda d: d.execute_script('return document.readyState') == 'complete')
如果需要的话,我应该在代码中的什么位置放置此行?
我再次运行了我的代码,这是第二次它工作了。输出是:
Rows length
16
cols length
6
col_name.text =
Name
cols length
6
col_name.text =
Address
cols length
6
col_name.text =
DOB
...
所以我需要改进我的代码,以便每次运行测试用例时它都能工作。 最好的解决方案是什么?
谢谢, 里亚兹
最佳答案
StaleElementReferenceException:消息:元素不再有效可能意味着页面未完全加载或更改页面元素的脚本未完成运行,因此元素仍在更改或未更改当您开始与他们互动后,所有这些都在场。
你走在正确的道路上!使用显式等待是避免 StaleElementReferenceException 和 NoSuchElementException 的好习惯,因为您的脚本执行命令的速度通常比网页加载或 JavaScript 代码完成的速度快得多。
在使用 WebDriver 命令之前先使用 WebDriverWait。
以下是不同“预期条件”的列表,您可以使用它来检测页面是否已完全加载或至少加载得足够:http://selenium-python.readthedocs.org/en/latest/waits.html
在代码中放置等待的示例,例如等待所有“td”元素完成加载 10 秒(您可能需要使用不同类型的条件、时间量或等待不同的元素,具体取决于网页的整体情况):
from selenium.webdriver.support import expected_conditions as EC
def get_variables_col_values(self):
try:
WebDriverWait(self.driver, 10).until(EC.presence_of_all_elements_located((By.TAG_NAME,'td')))
table_id = self.driver.find_element(By.ID, 'data_configuration_variables_ct_fields_body1')
#time.sleep(10)
rows = table_id.find_elements(By.TAG_NAME, "tr")
print "Rows length"
print len(rows)
for row in rows:
# Get the columns
print "cols length"
print len(row.find_elements(By.TAG_NAME, "td"))
col_name = row.find_elements(By.TAG_NAME, "td")[1] # This is the Name column print "col_name.text = "
print col_name.text
except NoSuchElementException, e:
return False
关于python-2.7 - Selenium Python 循环遍历表来打印我得到的列值 元素不再有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32149887/