【问题标题】:How to click on link with Python and Selenium successfully?如何成功单击与 Python 和 Selenium 的链接?
【发布时间】: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


【解决方案1】:

如果页面包含超过 2 行,它不一定会引发异常:O

links 列表包含 2 个值(index-0index-1)。如果第三个rowcol 不包含字符串“Yes”,则您不包含for 循环中的break 并递增index 变量。

所以在第三个 row index = 2 和 links 列表在 index-2 处没有任何内容,因此您会得到 IndexError

为什么不循环遍历链接呢?

found = False
for link in links:
    link.click()
    rows = page_html.find_all('tr',recursive=False)
    for row in rows:
        col = row.select('td:nth-of-type(5)')
        for string in col[0].strings:
            if (string == 'Yes'):
                found = True
                break
        if found:
            break
    if found:
        break

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 2021-12-03
    • 2016-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多