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

Python循环遍历BeautifulSoup对象获取aria-label值求助

问题解决:用BeautifulSoup提取aria-label属性值

你的Python代码报错是因为products里的每个元素是BeautifulSoup的Tag对象,不是字符串,所以不能直接调用split()方法。JavaScript里你是把DOM元素转成字符串处理,但Python用BeautifulSoup的话,直接操作DOM节点更简单可靠。

正确实现代码

from bs4 import BeautifulSoup

# 假设你已经拿到了response.text
products = BeautifulSoup(response.text, "html.parser").findAll("div", {"data-rubrik":"Cars"})

for product in products:
    # 找到当前div下的a标签
    a_tag = product.find("a")
    if a_tag:
        # 获取aria-label属性值,get方法可以避免属性不存在时报错
        car_name = a_tag.get("aria-label")
        if car_name:
            print(car_name)

为什么这能行?

  • product.find("a"):从每个div标签里直接查找子级的a标签,这是BeautifulSoup专门用来解析DOM的方法,比字符串分割靠谱得多。
  • a_tag.get("aria-label"):安全获取标签的属性值,如果a标签没有aria-label属性,会返回None,不会抛出异常。

可选:简化写法

如果确定每个div里一定有带aria-label的a标签,也可以写成一行:

for product in products:
    print(product.find("a")["aria-label"])

不过这种写法如果遇到没有a标签或没有属性的情况会报错,建议用第一种带判断的写法更稳健。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 00:15:42