【问题标题】:Selenium/xpath attaining text from dropdown menuSelenium/xpath 从下拉菜单中获取文本
【发布时间】:2014-07-16 00:51:50
【问题描述】:

在 Selenium 中,有没有办法从下拉菜单中获取文本,然后将其放入 Python 中的列表中?

假设:

<select id="zoo">
    <option value="30">
    Lion
    </option>

    <option value="10">
    Elephant
    </option>

    <option value="5">
    Zebra
    </option>
</select>

如何将 Lion、Elephant 和 Zebra 放入列表中?

【问题讨论】:

    标签: python html selenium xpath


    【解决方案1】:

    使用selenium.webdriver.support.select.Select() 并获取.options

    options

    返回属于此选择标签的所有选项的列表

    from selenium.webdriver.support.select import Select
    
    select = Select(driver.find_element_by_id('zoo'))
    print [option.text for option in select.options]
    

    其中driverwebdriver 实例。

    DEMO(使用 this w3schools page(是的,对不起 w3schools :)):

    >>> from selenium import webdriver
    >>> from selenium.webdriver.support.select import Select
    >>> driver = webdriver.Firefox()
    >>> driver.get('http://www.w3schools.com/tags/tryit.asp?filename=tryhtml_select')
    >>> driver.switch_to.frame('view')
    >>> select = Select(driver.find_element_by_tag_name('select'))
    >>> [option.text for option in select.options]
    [u'Volvo', u'Saab', u'Opel', u'Audi']
    

    请注意,此页面上的select 元素没有id,所以我只是使用find_element_by_tag_name() 找到它。另请注意,那里有iframes,所以我必须切换到适当的iframe 才能找到该元素。

    希望对您有所帮助。

    【讨论】:

    • 非常感谢您的帮助。但是,我确实不断收到相同的错误:TypeError: iteration over non-sequence 也许我没有成功找到 Select 元素?
    • @user2631667 不客气,你能显示你正在使用的代码和完整的错误回溯吗?会帮忙的。谢谢。
    【解决方案2】:

    这对我有用:

    select = Select(driver.find_element_by_tag_name('select'))
    
    text_list = []
    
    for option in select.find_elements_by_tag_name('option'):
        text_list.append(option.text)
    

    感谢您的帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-31
      • 1970-01-01
      • 2017-09-02
      相关资源
      最近更新 更多