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

Python中从Selenium链接列表筛选特定匹配项报错解决

解决Selenium筛选链接时的AttributeError问题

这个错误的核心原因是你生成的links列表里混有None值——页面上部分<a>标签没有设置href属性,调用elem.get_attribute("href")时会返回None,而None对象没有startswith方法,自然触发报错。

下面给三种可行的解决办法:

1. 生成链接列表时直接过滤空值

修改获取链接的代码,只保留有有效href的元素:

links = [elem.get_attribute("href") for elem in driver.find_elements(By.TAG_NAME,"a") if elem.get_attribute("href") is not None]

2. 筛选时先判断非空

如果不想改动原有的链接生成逻辑,就在筛选的列表推导式里先排除None:

[x for x in links if x is not None and x.startswith('https://www.sportingindex.com/spread-betting/football/international-world-cup/group_a')]

3. 直接定位目标链接(推荐)

用CSS选择器直接定位href以指定前缀开头的<a>标签,一步到位拿到符合要求的链接,既避免空值问题,又减少不必要的元素获取:

target_links = [elem.get_attribute("href") for elem in driver.find_elements(By.CSS_SELECTOR, 'a[href^="https://www.sportingindex.com/spread-betting/football/international-world-cup/group_a"]')]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 01:31:08