Python Selenium - 列表索引超出范围
Python Selenium - list index out of range
我是第一次尝试 Selenium。
我在尝试访问元素列表时遇到了一个奇怪的问题。
我有一个 HTML table(1 行,7 列),我想访问精确行的精确列。这是工作代码:
table_id = driver.find_element(By.CLASS_NAME, "table_class")
rows = table_id.find_elements(By.TAG_NAME, "tr")
for row in rows: # not necessary, I only have 1 row
cols = row.find_elements(By.TAG_NAME, "td")
for col in cols: # not necessary, I only need to access the 5th elem
print(col.text)
问题是,如果我尝试使用索引,它不起作用
cols = rows[0].find_elements(By.TAG_NAME, "td")
for col in cols:
print(col.text)
或者,如果我尝试使用 cols[4]
仅访问第 5 列,我总是得到 list index out of range
。
我不明白为什么它可以使用 for 循环工作,但我无法使用索引访问。
谢谢
我认为您正在尝试访问 row
变量,该变量仅为迭代循环而定义。不应该是cols = rows[0].find_elements(By.TAG_NAME, "td")
吗?
确保只有一排。可能是因为您使用了 for 循环,它遍历了您要查找的元素为空的行,因此返回一个空列表并向您显示错误。
另一个解决方案是,尝试通过 XPATH 访问元素。
rows = table_id.find_elements_by_xpath("""""")
对 cols
变量也做同样的事情。
我是第一次尝试 Selenium。 我在尝试访问元素列表时遇到了一个奇怪的问题。
我有一个 HTML table(1 行,7 列),我想访问精确行的精确列。这是工作代码:
table_id = driver.find_element(By.CLASS_NAME, "table_class")
rows = table_id.find_elements(By.TAG_NAME, "tr")
for row in rows: # not necessary, I only have 1 row
cols = row.find_elements(By.TAG_NAME, "td")
for col in cols: # not necessary, I only need to access the 5th elem
print(col.text)
问题是,如果我尝试使用索引,它不起作用
cols = rows[0].find_elements(By.TAG_NAME, "td")
for col in cols:
print(col.text)
或者,如果我尝试使用 cols[4]
仅访问第 5 列,我总是得到 list index out of range
。
我不明白为什么它可以使用 for 循环工作,但我无法使用索引访问。
谢谢
我认为您正在尝试访问 row
变量,该变量仅为迭代循环而定义。不应该是cols = rows[0].find_elements(By.TAG_NAME, "td")
吗?
确保只有一排。可能是因为您使用了 for 循环,它遍历了您要查找的元素为空的行,因此返回一个空列表并向您显示错误。
另一个解决方案是,尝试通过 XPATH 访问元素。
rows = table_id.find_elements_by_xpath("""""")
对 cols
变量也做同样的事情。