Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Listing select option values with Selenium and Python

I have the following HTML code

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

I am trying to get a list of the option values (like 459, 100, etc, not the text) using Selenium.

At the moment I have the following Python code

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

As you can see the code returns pure HTML, which I am parsing with HTMLParser library. Is there any way to get the option values just using Selenium? In other words, without having to parse the result from Selenium?

like image 657
Leonardo Cardoso Avatar asked Aug 29 '13 15:08

Leonardo Cardoso


People also ask

How do I select a class in Selenium Python?

We can select a drop-down menu option value with Selenium webdriver. The Select class in Selenium is used to handle drop-down. In an html document, the drop-down is identified with the <select> tag. Let us see the html structure of a drop-down.

How do I select all values from a dropdown in Selenium?

We can extract all the options in a dropdown in Selenium with the help of Select class which has the getOptions() method. This retrieves all the options on a Select tag and returns a list of web elements. This method does not accept any arguments.


1 Answers

check it out, here is how i did it before i knew what the Select Module did

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

outputs like this

-1
459
100
300
like image 101
TehTris Avatar answered Oct 23 '22 18:10

TehTris