You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

使用Beautiful Soup提取Coop网站价格单位(st)失败的技术求助

解决Beautiful Soup提取价格及单位"st"的问题

你现在只拿到价格数字,大概率是因为价格和单位"st"被拆到不同的标签(或者同一个父容器下的不同子元素)里了,你的现有代码只定位到了包含价格数字的Splash-content span,自然拿不到后面的单位。下面给你几种针对性的解决方案,你可以根据实际的HTML结构来选:

情况1:价格和单位在同一个父容器的不同子标签里

比如页面的HTML结构大概是这样的:

<div class="price-wrapper">
  <span class="Splash-content">29.90</span>
  <span class="price-unit">st</span>
</div>

你可以先定位到它们的父容器,再把两个标签的文本拼接起来:

# 先找到包含价格和单位的父元素(注意:这里的class要换成你实际查到的父容器class)
price_container = product.find('div', class_='price-wrapper')
# 提取所有子span的文本并拼接
full_price = ' '.join([item.text.strip() for item in price_container.find_all('span')])
print(full_price)  # 输出类似 "29.90 st"

情况2:价格和单位在同一个Splash-content span里

如果单位和价格是嵌套在同一个Splash-content标签下的子元素里,比如:

<span class="Splash-content">
  <span>29.90</span>
  <span>st</span>
</span>

那你只需要直接获取整个Splash-content的文本即可,Beautiful Soup会自动合并所有子标签的内容:

test = product.find('span', class_='Splash-content')
full_price = test.text.strip()
print(full_price)  # 输出 "29.90 st"

情况3:单位是Splash-content的兄弟元素

如果单位标签跟Splash-content是平级的兄弟关系,比如:

<span class="Splash-content">29.90</span>
<span class="unit-tag">st</span>

可以用find_next_sibling()方法获取相邻的单位标签:

price_span = product.find('span', class_='Splash-content')
# 获取下一个兄弟span标签(如果单位标签不是span,记得修改标签名)
unit_span = price_span.find_next_sibling('span')
full_price = f"{price_span.text.strip()} {unit_span.text.strip()}"
print(full_price)

小提示

你可以用浏览器的开发者工具(按F12)查看目标元素的真实HTML结构:右键点击页面上的价格+单位区域,选择「检查」,就能看到它们的标签层级关系,这样就能精准定位啦~

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

火山引擎 最新活动