我有一个 HTML,它有多个选择标签和每个选择标签下的多个下拉选项
我想解析每个选择下的所有选项并存储它们
这是 html 的样子
<select name="primary_select">
<option></option>
<option></option>
</select>
<select name="secondary_select">
<option></option>
<option></option>
</select>
这是我的代码的样子
我在python中使用beautifulsoup和mechanize
汤 = BeautifulSoup(response.get_data())
subject_options = soup.findAll('select', attrs = {'name': 'primary_select'} ).findAll("option")
print subject_options
我收到以下错误
AttributeError: 'ResultSet' object has no attribute 'findAll'
谢谢你的帮助:)
最佳答案
findAll
返回一个列表,您不能在其中直接应用另一个 findAll。
from bs4 import BeautifulSoup
html = '''<select name="primary_select">
<option></option>
<option></option>
</select>
<select name="secondary_select">
<option></option>
<option></option>
</select>'''
soup = BeautifulSoup(html)
subject_options = [i.findAll('option') for i in soup.findAll('select', attrs = {'name': 'primary_select'} )]
print subject_options
输出:
[[<option></option>, <option></option>]]
或者
使用 css 选择器。
soup = BeautifulSoup(html)
subject_options = soup.select('select[name=primary_select] > option')
print subject_options
I want to parse all the options under each select and store them.
subject_options = soup.select('select > option')
print subject_options
输出:
[<option></option>, <option></option>, <option></option>, <option></option>]
关于python - 解析 BeautifulSoup 中 select 下的所有选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31511333/