如何获取表中的行数?

2024-10-01 11:28:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用selenium python获取网页上表的行数。 我试着用下面的方式描述这里:How to count no of rows in table from web application using selenium python webdriver

rows=len(driver.find_element_by_xpath("//table[@id='SheetContentPlaceHolder_GridView1']/tbody/tr"))

我得到的结果如下:

rows=len(driver.find_element_by_xpath("//table[@id='SheetContentPlaceHolder_GridView1']/tbody/tr"))
TypeError: object of type 'FirefoxWebElement' has no len()

我不明白我做错了什么

谢谢你的帮助


Tags: ofnoidbylendriverseleniumtable
2条回答

find_element_by_xpath()将返回单个元素,当您使用FireFox时,将返回第一个匹配的WebElement,它可以传递给len()。因此,您会看到错误:

TypeError: object of type 'FirefoxWebElement' has no len()

因此,您需要使用find_elements_by_xpath()而不是find_element_by_xpath(),它将返回一个列表


理想情况下,要使用Selenium和Python提取js表中的行数,您必须为visibility_of_all_elements_located()引入WebDriverWait,并且可以使用以下任一解决方案:

  • 使用XPATH

    print(len(WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//table[@id='SheetContentPlaceHolder_GridView1']/tbody/tr")))))
    
  • 注意:您必须添加以下导入:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    

方法driver.find_element_by_xpath(...)只返回表的第一个子项(行)

将行更改为driver.find_elements_by_xpath(...)。它返回一个元素列表。因此,新代码将是:

rows = driver.find_elements_by_xpath("//table[@id='SheetContentPlaceHolder_GridView1']/tbody/tr")
number_of_rows = len(rows)

相关问题 更多 >