问题
I've generated a list with all tags of my HTML file called 'option'. But I can't get the values inside the tag.
This is my code and data:
>>> soup2 = soup.findAll('option')
>>> soup2
[
<option value="ufs_munic"> Por Município </option>,
<option value="ext_paises"> Por País </option>,
...
]
I'd like to get the quoted values after option value= in each tag.
For example:
ufs_munic
ext_paises
5
6
7
8
9
...
回答1:
Using a list comprehension, you can get all the values from the options using the get method:
>>> soup2 = [option.get('value') for option in soup.findAll('option')]
>>> soup2
['ufs_munic', 'ext_paises', '5', '6', '7', '8', '9', ...]
You can even pass a default value if the option has no option defined:
option.get('value', 'There is no value!')
回答2:
>>> for item in soup2:
... print item['value']
来源:https://stackoverflow.com/questions/9027737/get-value-attribute-for-each-tag-found-using-tag-find-all