列出使用Selenium和Python选择选项值

时间:2013-08-29 15:56:57

标签: python selenium

我有以下HTML代码

<select name="countries" class_id="countries">
    <option value="-1">--SELECT COUNTRY--</option>
    <option value="459">New Zealand</option>
    <option value="100">USA</option>
    <option value="300">UK</option>
</select>

我正在尝试使用Selenium获取选项值列表(如459,100等,而不是文本)。

目前我有以下Python代码

from selenium import webdriver

def country_values(website_url):
    browser = webdriver.Firefox()
    browser.get(website_url)
    html_code=browser.find_elements_by_xpath("//select[@name='countries']")[0].get_attribute("innerHTML")
    return html_code

正如您所看到的,代码返回纯HTML,我正在使用HTMLParser库进行解析。有没有办法只使用Selenium来获取选项值?换句话说,无需解析Selenium的结果?

4 个答案:

答案 0 :(得分:15)

检查出来,这是我在知道Select Module做了什么之前的做法

from selenium import webdriver

browser = webdriver.Firefox()
#code to get you to the page

select_box = browser.find_element_by_name("countries") 
# if your select_box has a name.. why use xpath?..... 
# this step could use either xpath or name, but name is sooo much easier.

options = [x for x in select_box.find_elements_by_tag_name("option")]
# this part is cool, because it searches the elements contained inside of select_box 
# and then adds them to the list options if they have the tag name "options"

for element in options:
    print element.get_attribute("value") 
    # or append to list or whatever you want here

像这样输出

-1
459
100
300

答案 1 :(得分:7)

import selenium.webdriver as webdriver
import selenium.webdriver.support.ui as UI
import contextlib

with contextlib.closing(webdriver.Firefox()) as driver:
    driver.get(url)
    select = UI.Select(driver.find_element_by_xpath('//select[@name="countries"]'))
    for option in select.options:
        print(option.text, option.get_attribute('value'))  

打印

(u'--SELECT COUNTRY--', u'-1')
(u'New Zealand', u'459')
(u'USA', u'100')
(u'UK', u'300')

我学到了here。另请参阅the docs

答案 2 :(得分:4)

更简单的版本:

dropdown_menu = Select(driver.find_element_by_name(<NAME>))
for option in dropdown_menu.options:
        print option.text

答案 3 :(得分:0)

稍微改进的答案。 在 Selenium 和 Python 中,如果要获取所有属性值,请使用以下列表推导式:

options = [x.get_attribute("value") for x in driver.find_element_by_id("yourlocator").find_elements_by_tag_name("option")]
print(options)

.text 的简单调用不适用于列表。 使用:

options = [x.get_attribute("innerText") for x in driver.find_element_by_id("yourlocator").find_elements_by_tag_name("option")]
print(options)