0

Is there any way I could select all the <option>s in the following HTML form <select> into a python list, like so, ['a','b','c','d']?

<select name="sel">
 <option value="a">a</option>
 <option value="b">b</option>
 <option value="c">c</option>
 <option value="d">d</option>
</select>

Many thanks in advance.

martineau
124k29 gold badges181 silver badges319 bronze badges
asked Dec 6, 2010 at 19:06
0

2 Answers 2

5
import re
text = '''<select name="sel">
 <option value="a">a</option>
 <option value="b">b</option>
 <option value="c">c</option>
 <option value="d">d</option>
</select>'''
pattern = re.compile(r'<option value="(?P<val>.*?)">(?P=val)</option>')
handy_list = pattern.findall(text)
print handy_list

will output

['a', 'b', 'c', 'd']

Disclaimer: Parsing HTML with regular expressions does not work in the general case.

answered Dec 6, 2010 at 19:14
Sign up to request clarification or add additional context in comments.

Comments

3

You might want to look at BeautifulSoup if you want to parse other HTML data also

from BeautifulSoup import BeautifulSoup
text = '''<select name="sel">
 <option value="a">a</option>
 <option value="b">b</option>
 <option value="c">c</option>
 <option value="d">d</option>
</select>'''
soup = BeautifulSoup(text)
print [i.string for i in soup.findAll('option')]
answered Dec 6, 2010 at 19:50

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.