解析 BeautifulSoup 中 select 下的所有选项

parsing all options under select in BeautifulSoup

我有一个 HTML,它有多个 select 标签和每个 select 标签下的多个下拉选项 我想解析每个 select 下的所有选项并存储它们

这就是 html 的样子

<select name="primary_select">
    <option></option>
    <option></option>
</select>
<select name="secondary_select">
    <option></option>
    <option></option>
</select>

这就是我的代码的样子

我正在使用 beautifulsoup 并在 python

中进行机械化

汤=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 returns 无法在其中直接应用另一个 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>]

是的,ResultSet 没有属性 findAll...

这应该有效:

subject_options = [
    r.findAll('option')
    for r in soup.findAll('select', attrs = {'name': 'primary_select'} )
]

但是你为什么不做一个单一的请求从一开始就获得选项?

subject_options = soup.findAll(
    lambda t: t.name == 'option' and t.parent.attrs.get('name') == 'primary_select'
)

一个简单的修改解决了问题

我只需要添加一个 [0],因为它给出了符合条件的所有元素的列表

感谢您的帮助:)

 subject_options = soup.findAll('select', attrs = {'name': 'primary_select'} )[0].findAll("option")

感谢压缩脚本

为了获取所选选项的实际值,我发现它可以与 .getText() 函数一起使用,以防有人也想扩展它。

代码:

subject_options = soup.select('select[aria-label=Seitenauswahl] > option')

for i in subject_options:
    print(i.getText())

max_pagnation=subject_options[-1].getText()
print("Max=" + max_pagnation)

输出

1
2
3

Max=3