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

使用此代码,我需要值而'0'不是文本'2002/12'

我尝试了很多 BS4 选项,, , .stripped_strings,.strip()等。.contentsget()

我怎样才能得到值而不是文本?

4

2 回答 2

25

你想要value 属性;使用映射语法访问标签属性:

option['value']

演示:

>>> 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
于 2013-10-15T23:03:54.507 回答
4

像这样:

>>> import BeautifulSoup
>>> doc = """
... <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 = BeautifulSoup.BeautifulSoup(doc)
>>> list = soup.findAll('option')
>>> for l in list:
...   print l['value']
... 
0
1
2
3
4
5
>>> 
于 2013-10-15T23:08:17.587 回答