Get value attribute for each tag found using Tag.find_all()

穿精又带淫゛_ 提交于 2020-01-06 08:45:26

问题


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">&nbsp;&nbsp;Por Município&nbsp;&nbsp;</option>,
  <option value="ext_paises">&nbsp;&nbsp;Por País&nbsp;&nbsp;</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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!