【问题标题】:How to treat a single row of table rows: as a web element or a list of web elements (python)如何处理单行表格行:作为 web 元素或 web 元素列表(python)
【发布时间】:2018-04-21 01:54:56
【问题描述】:

我从表中获取行,例如:

def get_rows_from_table(self) -> List[WebElement]:       
    table_rows = self.table.find_elements(By.TAG_NAME, "tr")       
    return table_rows

table_rowsList[WebElement],单行有很多单元格,所以单行本身也应该是一个列表。因此,当我写这样的东西时:

def get_a_specific_row_from_table(self, table_rows, row_num: int) -> List[WebElement]:            
    return table_rows[row_num - 1]

我收到一个错误:Expected type 'List[WebElement]', got 'WebElement' instead => 这是因为该 List 中的一个元素被定义为 WebElement。

如果我想得到一个单元格,它应该是这样的:

cell = table_row[1]

那么这一行就是一个列表。我的问题是:我们应该如何对待单行表行?作为元素还是元素列表?将所有表行定义为List[List[WebElement]]

【问题讨论】:

    标签: python selenium selenium-webdriver html-table


    【解决方案1】:

    来自(Java)documentation

    使用给定的查找当前上下文中的所有元素 机制。使用 xpath 时请注意 webdriver 遵循标准 约定:以“//”为前缀的搜索将搜索整个 文档,而不仅仅是当前节点的子节点。使用“.//”来 将您的搜索限制在此 WebElement 的子项中。这种方法是 受当时有效的“隐式等待”时间的影响 执行。当隐式等待时,此方法将立即返回 找到的集合中有超过 0 个项目,或者将返回一个 如果达到超时,则为空列表。

    Specified by:
        findElements in interface SearchContext
    Parameters:
        by - The locating mechanism to use
    Returns:
        A list of all WebElements, or an empty list if nothing matches.
    

    所以,你有一个 webelements 列表是正确的。

    例如,如果您的 html 是这样的:

    <!DOCTYPE html>
    <html>
    <head>
    <style>
    table, th, td {
        border: 1px solid black;
    }
    </style>
    </head>
    <body>
    
    <table>
      <tr>
        <th>Month</th>
        <th>Savings</th>
      </tr>
      <tr>
        <td>January</td>
        <td>$100</td>
      </tr>
      <tr>
        <td>February</td>
        <td>$80</td>
        <td>$100</td>
      </tr>
    </table>
    
    </body>
    </html>
    

    并且您想为每个tr 迭代所有td

    trList= driver.find_elements(By.TAG_NAME, "tr")
    print("len trList: " + str(len(trList)))
    i=0
    for tr in trList:
        tdList= tr.find_elements(By.TAG_NAME, "td")
        print("len tdList: " + str(len(tdList)))
        print ("value: " + tr.text)
        print ("-----------------"+str(i)+"------------")
        i=i+1
    

    输出将是:

    len trList: 3
    -----------------
    len tdList: 0
    value: Month Savings
    -----------------0------------
    len tdList: 2
    value: January $100
    -----------------1------------
    len tdList: 3
    value: February $80 $100
    -----------------2------------
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-14
      相关资源
      最近更新 更多