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

如何在Python Selenium中获取<a>标签的href属性?

解决Selenium获取href属性的AttributeError问题

你出错的原因很直接:Selenium的WebElement对象没有getattr方法,这是Python的内置函数,不是用来获取元素属性的。浏览器控制台用的是JS的getAttribute(),对应Python Selenium里的方法是get_attribute(),把代码里的getattr换成get_attribute就可以正常获取href了。

修正后的代码

handle_browser.find_elements(By.CLASS_NAME,'item-panel__title')[0].get_attribute('href')

更简洁的写法

既然你只需要第一个匹配的元素,用find_element(单数)更直接,不用再取索引:

handle_browser.find_element(By.CLASS_NAME,'item-panel__title').get_attribute('href')

额外方式:执行JavaScript获取

如果你习惯用浏览器控制台的JS逻辑,也可以在Selenium里直接执行同样的JS代码:

href = handle_browser.execute_script("return document.getElementsByClassName('item-panel__title')[0].getAttribute('href')")

对应的HTML结构:

<a class="item-panel__title" href="/u/abcd" rel="">@abcd</a>
<div class="item-panel__description">abcd</div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 08:10:52