2013-08-29 52 views
7

Tôi có đoạn code HTML sauListing chọn giá trị tùy chọn với Selenium và Python

<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> 

tôi đang cố gắng để có được một danh sách các giá trị tùy chọn (như 459, 100, vv, không phải là văn bản) sử dụng Selenium.

Tại thời điểm tôi có mã Python sau

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 

Như bạn có thể thấy mã trả về HTML thuần túy, mà tôi đang phân tích với thư viện HTMLParser. Có cách nào để có được các giá trị tùy chọn chỉ sử dụng Selenium không? Nói cách khác, không phải phân tích kết quả từ Selenium?

Trả lời

14

kiểm tra xem nó ra, đây là cách tôi đã làm nó trước khi tôi biết những gì Select Mô-đun đã

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 

kết quả đầu ra như

-1 
459 
100 
300 
+1

Mã hoạt động, cảm ơn bạn rất nhiều! Đó là một cách rất dễ dàng để làm việc thực sự. –

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')) 

in

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

tôi đã học here này. Xem thêm the docs.

+0

Và nó công trinh! :) Vâng, tôi sẽ đọc các tài liệu nhiều hơn một chút, tôi không thể có được lựa chọn để hoạt động đúng khi tôi đã cố gắng. Cảm ơn bạn! –

2

đơn giản hơn phiên bản này:

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