Wednesday, 15 June 2011

python - Find the selected option using BeautifulSoup -



python - Find the selected option using BeautifulSoup -

i selected options of select. example:

<select> <option value="0">2002/12</option> <option value="1">2003/12</option> <option value="2">2004/12</option> <option value="3">2005/12</option> <option value="4">2006/12</option> <option value="5" selected>2007/12</option> </select>

i know can do

theselecttag.findall('option',attrs={'selected':''})

but returning options. there way elements attribute exists? please note, inquire all, site i'm scraping include selected attribute multiple options.

i'm using python 2.7 , beautiful soup 4.1.2

passing true attribute's value match elements attribute:

>>> bs4 import beautifulsoup >>> soup = beautifulsoup('''<select> ... <option value="0">2002/12</option> ... <option value="1">2003/12</option> ... <option value="2">2004/12</option> ... <option value="3">2005/12</option> ... <option value="4">2006/12</option> ... <option value="5" selected>2007/12</option> ... </select>''') >>> soup.find_all('option', selected=true) [<option selected="" value="5">2007/12</option>] >>> soup.find_all('option', {'selected': true}) [<option selected="" value="5">2007/12</option>]

and lxml:

>>> lxml import etree >>> root = etree.html('''<select> <option value="0">2002/12</option> <option value="1">2003/12</option> <option value="2">2004/12</option> <option value="3">2005/12</option> <option value="4">2006/12</option> <option value="5" selected>2007/12</option> </select>''') >>> root.xpath('//option[@selected]') [<element alternative @ 0x228b7d0>]

python beautifulsoup

No comments:

Post a Comment