如何使用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&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
相关产品推荐
相关产品推荐

