Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python BeautifulSoup get select.value not text

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

with this code, I need value as '0' not text as '2002/12'

I tried a lot of BS4 options, .stripped_strings, .strip(), .contents, get(), etc.

How I can get values not text?

like image 489
joseph Avatar asked Oct 15 '13 22:10

joseph


1 Answers

You want the value attribute; access tag attributes using mapping syntax:

option['value']

Demo:

>>> from 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>
... ''')
>>> for option in soup.find_all('option'):
...     print 'value: {}, text: {}'.format(option['value'], option.text)
... 
value: 0, text: 2002/12
value: 1, text: 2003/12
value: 2, text: 2004/12
value: 3, text: 2005/12
value: 4, text: 2006/12
value: 5, text: 2007/12
like image 87
Martijn Pieters Avatar answered Sep 20 '22 08:09

Martijn Pieters