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

