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

如何使用Beautiful Soup获取where-to-watch-meta标签的affiliate属性值

提取where-to-watch-meta标签的affiliate属性值

问题分析

你提供的原Python代码存在两处错误:

  • 错误使用property="image"作为查找条件,但目标<where-to-watch-meta>标签并不包含该属性
  • 试图提取content属性,而实际需要的是affiliate属性

正确实现代码

以下是使用Beautiful Soup提取affiliate属性值的正确写法:

from bs4 import BeautifulSoup

# 替换为你的实际HTML内容
html_content = """
<p>
Buy
Seasons 1-2
</p>
<where-to-watch-meta
  href="https://www.kmtrak.com/SM94M2/3HWS9F7/?uid=233&amp;cmp=rt_where_to_watch"
  affiliate="hulu"
  skeleton="panel"
  data-qa="affiliate-item">
  <where-to-watch-bubble
    image="hulu"
    slot="bubble"
    tabindex="-1"
  ></where-to-watch-bubble>
  <span slot="license">Subscription</span>
  <span slot="coverage">Seasons 1-2</span>
</where-to-watch-meta>
"""

# 解析HTML
soup = BeautifulSoup(html_content, "html.parser")

# 查找目标标签并提取affiliate属性值
onde_assistir = soup.find("where-to-watch-meta")["affiliate"]
print(onde_assistir)  # 输出结果:hulu

容错处理

如果担心目标标签可能不存在,导致抛出KeyError或AttributeError,可以使用get()方法做容错处理:

# 若标签不存在则返回None
onde_assistir = soup.find("where-to-watch-meta").get("affiliate", None)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 07:55:16