python - 解析 BeautifulSoup 中 select 下的所有选项

标签 python python-2.7 web-scraping beautifulsoup mechanize

我有一个 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/

相关文章:

python - 计算 x1 ^ (x2 ^ (x3 ^ (... ^ xn))) 的最后一位(十进制)数字

python - 将 numpy 数组写入具有特定列数的 csv 文件

python - ast.literal_eval 用于 python 中的变量?

python - 我对 tkinter python gui 元素有一个小问题

python - 如果存在特定单词,则将行值替换为 NaN - Python

python - imp.load_source 另一个文件而不是 .py ,但 .py 也存在于该目录中

python-2.7 - Flask登录 'function'对象没有属性 'is_active'

javascript - VBA动态网页抓取Excel

python - 检索页面中所有外部对象的 URL,包括。动态加载

python - 如何仅抓取同一类中的某些标签?