2

I am receiving data from a web service and its replying me data in html form.The response data i am getting is this dropdown:

<span>

        <select name="country" id="country" class="text " style="width:170px;">
                        <option value="">-Select country-</option>
                                <option value="Russia" >Russia</option>
                                <option value="America" >America</option>
                                <option value="Spain" >Spain</option>
                                <option value="France" >France</option>
                                <option value="X - 15" >X - 15</option>


        </select>
</span>

I need to further process on this data and get option values in python list.How can i select all country names and collect them into a python list?

3
  • possible duplicate of Parsing HTML in Python Commented Jan 26, 2012 at 8:09
  • If you're getting an html response, you don't need regexps but an xml/html parser. Commented Jan 26, 2012 at 8:17
  • If you plan to use regex for parsing HTML, please read this: stackoverflow.com/questions/1732348/… Commented Jan 26, 2012 at 8:33

2 Answers 2

3

Check out beautiful soup.

In this case, you could do the following assuming you had your html block in the html var as a string:

 >>> import BeautifulSoup as bs
 >>>  
 >>>  html = bs.BeautifulSoup(html)
 >>>  html.findAll('option')

For even more syntactic sugar, check out soupselect.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks mvanveen.......i will use beautifulSoup when i have to parse more HTML data.
html.findAll('option') instead of a.findAll('option')
Nice catch, sorry about that! Edited.
0
import re

pattern = r"<option value=\"(.*)\" >"
val=re.findall(pattern,htmlCode)

val will contain a list of all values

Based on your example html code, the above regex findall should do the job for you, however if you are doing a lot of extensive html code parsing then usually regex are not an good option. But for a simple case like yours this is the best option.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.