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

如何使用Python Selenium提取元素的aria-label属性值?

修正代码:提取元素的aria-label属性值

你的问题出在get_attribute()方法的参数使用错误——你传入了CSS选择器格式的[aria-label],但这个方法需要的是纯属性名称,也就是直接写"aria-label"。

修正后的代码如下:

try:
    Rating = driver.find_elements(By.CSS_SELECTOR,'div.b5cd09854e.d10a6220b4')
except:
    Rating = []  # 建议改为空列表,避免后续循环触发报错
Rating1 = []
for i in Rating:
    store = {
        'Rating': i.get_attribute("aria-label")  # 去掉方括号,直接传入属性名
    }
    Rating1.append(store)
print(Rating1)

额外优化提示:

  • 原代码中except块将Rating设为None,后续遍历会触发TypeError,改成空列表[]能让代码逻辑更顺畅。
  • 如果要处理元素无aria-label属性的情况,可以添加默认值兜底:i.get_attribute("aria-label") or "无评分",避免结果中出现None。

执行修正后的代码后,Rating1会输出每个目标元素对应的aria-label属性值,而非WebElement对象。

内容的提问来源于stack exchange,提问作者Mathematics physics Biology

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 04:15:51