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

网页爬虫项目出现KeyError: 'href'报错,请求技术协助

爬虫KeyError问题:找不到'href'属性

你的代码触发KeyError: 'href',核心原因是遍历的price_link集合里存在不含href属性的标签,直接通过tag['href']强制取值会触发报错。

解决方法

方法1:先判断属性存在再取值

通过检查tag.attrs中是否包含href,既能避免报错,还能排查异常标签:

property_prices = []
base_url = 'https://www.magicbricks.com/property-for-sale/residential-real-estate?bedroom=&proptype=Multistorey-Apartment,Builder-Floor-Apartment,Penthouse,Studio-Apartment&cityName=Aurangabad'

for tag in price_link:
    if 'href' in tag.attrs:
        property_prices.append(base_url + tag['href'])
    else:
        # 可选:打印无href的标签,定位问题来源
        print(f"发现无href属性的标签: {tag}")

方法2:用get()方法安全取值

get()方法在属性不存在时会返回None或你指定的默认值,写法更简洁:

property_prices = []
base_url = 'https://www.magicbricks.com/property-for-sale/residential-real-estate?bedroom=&proptype=Multistorey-Apartment,Builder-Floor-Apartment,Penthouse,Studio-Apartment&cityName=Aurangabad'

for tag in price_link:
    href = tag.get('href')
    if href:
        property_prices.append(base_url + href)

额外排查建议

检查price_link的获取逻辑:如果你的目标是抓取链接,应该明确筛选<a>标签(比如用soup.find_all('a')),避免把<div>、<span>这类本身不带href的标签混入集合。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 03:25:28