2013-08-29 10 views
7

Mam następujący kod HTMLListing wybierz wartości opcji z selenem i 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> 

Próbuję uzyskać listę wartości opcji (jak 459, 100, itd, a nie tekst) za pomocą selen.

Obecnie mam następujący kod 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 

Jak widać kod zwraca czysty HTML, który ja parsowania z biblioteką HTMLParser. Czy istnieje sposób na uzyskanie wartości opcji po prostu przy użyciu Selenium? Innymi słowy, bez konieczności analizowania wyniku z Selenium?

Odpowiedz

14

to sprawdzić, oto jak to zrobiłem przed Wiedziałem, co Select Module zrobił

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 

wyjścia jak ten

-1 
459 
100 
300 
+1

Kod działa, dziękuję bardzo! Jest to bardzo łatwy sposób na rzeczywistą pracę. –

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

drukuje

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

Nauczyłem się tej here. Zobacz także the docs.

+0

i to Prace! :) Tak, będę czytać dokumenty trochę więcej, nie mogłem uzyskać wyboru, aby działał poprawnie, gdy próbowałem. Dziękuję Ci! –

2

Prostsza wersja:

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