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

谷歌预览页爬取:如何用BeautifulSoup获取含Dimensions的元素类名?

搞定谷歌预览页产品维度提取的小技巧

嘿,我来帮你解决这个爬虫提取维度的问题!你已经找到包含“Dimensions”的文本节点了,接下来只需要顺着节点往上找它所属的元素,就能拿到对应的class名,然后顺利提取维度数据啦。

第一步:精准匹配包含“Dimensions”的文本

你用soup.find_all(text="Dimensions")可能会因为文本前后的空格、换行匹配不到,建议用正则表达式来做灵活匹配,比如:

import re
from bs4 import BeautifulSoup

html = """<span class="st"> Part Number, <b> DCD771B </b> . Item Weight, 2.8 pounds. Package <b> Dimensions </b> , 10.8 x <br/> 8.2 x 3.5 inches. Item model number, <b> DCD771B </b> . Power Source, battery-powered. </span> """
soup = BeautifulSoup(html, 'html.parser')

# 用正则匹配包含Dimensions的文本,自动忽略前后空格
dim_text_nodes = soup.find_all(text=re.compile(r'\s*Dimensions\s*'))

第二步:获取对应的元素类名

找到文本节点后,你可以通过节点的父元素/祖先元素来获取class属性:

  • 如果要拿直接父元素的class(比如例子里包裹Dimensions的<b>标签):
for node in dim_text_nodes:
    parent_class = node.parent.get('class')
    print(f"直接父元素的class: {parent_class}")
  • 如果要找上层的容器元素(比如整个产品信息所在的<span class="st">),可以用find_parent或者遍历祖先节点:
for node in dim_text_nodes:
    # 找到第一个带class属性的祖先元素
    container = node.find_parent(lambda tag: tag.has_attr('class'))
    container_class = container.get('class')
    print(f"上层容器的class: {container_class}")

第三步:提取具体的维度数值

拿到对应的容器元素后,就可以用正则提取维度的具体数值了:

for node in dim_text_nodes:
    container = node.find_parent('span')  # 或者更通用的祖先元素匹配
    # 匹配类似“10.8 x 8.2 x 3.5”的维度格式
    dim_match = re.search(r'(\d+\.?\d*)\s*x\s*(\d+\.?\d*)\s*x\s*(\d+\.?\d*)', container.text)
    if dim_match:
        length, width, height = dim_match.groups()
        print(f"提取到的产品维度:{length} × {width} × {height} inches")

额外小提示

如果“Dimensions”所在的元素层级不确定,可以遍历所有祖先节点,找到第一个带class的元素就停止:

for node in dim_text_nodes:
    for ancestor in node.parents:
        if ancestor.has_attr('class'):
            print(f"找到的目标元素class: {ancestor.get('class')}")
            break

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:59:07