You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用BeautifulSoup爬取产品品牌、口味信息并生成键值对

爬取实现方案

前置准备

  • 先安装所需依赖库,执行命令:pip install beautifulsoup4

完整可运行代码

from bs4 import BeautifulSoup

# 此处替换为你实际抓取到的页面HTML源码
page_html = '''
<tr class="a-spacing-small">
<td class="a-span3">
    <span class="a-size-base a-text-bold">Flavour</span>
</td>
<td class="a-span9">
    <span class="a-size-base">Green Apple</span>
</td>
</tr>
<tr class="a-spacing-small">
<td class="a-span3">
    <span class="a-size-base a-text-bold">Brand</span>
</td>
<td class="a-span9">
    <span class="a-size-base">Carabau</span>
</td>
</tr>
'''

# 初始化解析器
soup = BeautifulSoup(page_html, 'html.parser')
product_info = {}

# 遍历所有属性行提取键值
for attr_row in soup.find_all('tr', class_='a-spacing-small'):
    attr_name = attr_row.find('td', class_='a-span3').get_text(strip=True)
    attr_value = attr_row.find('td', class_='a-span9').get_text(strip=True)
    product_info[attr_name] = attr_value

# 按要求格式输出
for key, val in product_info.items():
    print(f"{key} - {val}")

输出效果

运行上述代码后会直接输出你需要的格式:

Flavour - Green Apple
Brand - Carabau

提取到的键值对同时会存在product_info字典中,可直接调用做后续处理。

内容的提问来源于stack exchange,提问作者Kanchan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 13:15:04