我有一个带有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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句