代码之家  ›  专栏  ›  技术社区  ›  Rob

Python Selenium-统计列表框中的项目数

  •  0
  • Rob  · 技术社区  · 7 年前

    我正在尝试计算网页列表框中的项目数,然后从该列表框中选择多个项目。我可以很好地选择项目,我只是在努力找出如何计算列表框中的项目。

    请参阅代码:

    from selenium import webdriver
    from selenium.webdriver.support.ui import Select
    

    ... ...

    accountListBox = Select(driver.find_element_by_id("ctl00_MainContent_accountItemsListBox"))
    accountListBox.select_by_index(0)
    
    print(len(accountListBox))
    

    我尝试使用len(),这会导致错误“TypeError:Select类型的对象没有len()”。

    我也试过accountListBox。size()并从第3行中删除了“Select”,这也不起作用。

    这是一个非常新的问题,所以非常感谢您的反馈。

    谢谢

    3 回复  |  直到 7 年前
        1
  •  1
  •   plamut Hadi Akbarzadeh    7 年前

    根据 docs 选择元素的选项列表可以通过以下方式获得 select.options . 在你的特殊情况下 accountListBox.options ,你需要打电话 len() 在…上 那个 ,而不是在 Select 实例本身:

    print(len(accountListBox.options))
    

    或者,如果只想打印当前选定选项的列表:

    print(len(accountListBox.all_selected_options))
    
        2
  •  0
  •   mathsicist    7 年前

    您应该使用 find_elements 通过对每个列表框的项目使用一些公共选择器来查找所有项目,将找到的元素存储到一个变量中,并使用本机python库对其进行计数。

        3
  •  0
  •   briancaffey    7 年前

    我通常用硒搭配靓汤。Beautiful Soup是一个Python包,用于解析HTML和XML文档。

    使用Beautiful Soup,您可以通过以下方式获得列表框中的项目数:

    from bs4 import BeautifulSoup
    from selenium import webdriver
    
    driver = webdriver.PhantomJS() # or webdriver.Firefox()
    driver.get('http://some-website.com/some-page/')
    
    html = driver.page_source.encode('utf-8')
    b = BeautifulSoup(html, 'lxml')
    items = b.find_all('p', attrs={'id':'ctl00_MainContent_accountItemsListBox'})
    print(len(items))
    

    我假设您要查找的DOM元素是段落( p 标记),但您可以将其替换为需要查找的任何元素。