【发布时间】:2021-01-29 06:16:09
【问题描述】:
我正在遍历行,每个行都有一个链接和一个我分配给它的索引值。除了 selenium,我也在使用 Beautiful Soup API 来检查页面 html。
主要问题是一旦我找到了我想要使用的链接索引,我执行links[index].click(),它只会偶尔工作。
Error:list index out of range
当我仔细检查时,我发现我的索引仍在列表范围内,但仍然无法正常工作
# Each link is confirmed to work, but only works every other time the script is run
page_html = BeautifulSoup(driver.page_source, 'html.parser')
links = [link1, link2]
rows = page_html.find_all('tr',recursive=False)
index = 0
found = False
for row in rows:
col = row.select('td:nth-of-type(5)')
for string in col[0].strings:
# If column has a "Yes" string, let's use the index of this row
if (string == 'Yes'):
found = True
break
# Break from loop if we already have the row that we want
if found:
break
# If not found, continue adding to index value
index += 1
# This is the part of the code that does not work consistently
links[index].click()
为了调试它,我尝试了以下操作:
def custom_wait(num=3):
driver.implicitly_wait(num)
time.sleep(num)
attempts = 0
while attempts < 10:
custom_wait()
try:
links[index].click()
except:
PrintException()
attempts += 1
else:
logger.debug("Link Successfully clicked")
break
当我运行此代码时,它表示链接已成功单击,但再次提及索引超出范围。
【问题讨论】:
-
索引从0开始,而不是1。第二次迭代必然会失败,因为没有链接[2]
标签: python selenium selenium-webdriver beautifulsoup selenium-chromedriver