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

Craigslist网页爬取报错:'NoneType' object has no attribute 'text',无法获取商品价格的问题求助

解决Craigslist爬取中价格获取的AttributeError问题

问题原因

这是网页爬取里很常见的“元素不存在”坑——Craigslist的部分帖子(尤其是你爬的服务类分类下)可能没有显示价格,导致find(class_='result-price')返回了None,这时再调用.text自然就触发了AttributeError。移除.text后显示None,也验证了这一点:确实找不到这个价格元素。

解决方案

我们需要先判断目标元素是否存在,再去获取文本;同时建议你遍历所有帖子(而不是只取第一个),收集完整的爬取数据。以下是修改后的完整代码:

import requests
from bs4 import BeautifulSoup
from django.shortcuts import render
from requests.compat import quote_plus
from . import models

BASE_CRAIGSLIST_URL = 'https://losangeles.craigslist.org/d/services/search/bbb?query={}'

def home(request):
    return render(request, 'base.html')

def new_search(request):
    search = request.POST.get('search')
    models.Search.objects.create(search=search)
    final_url = BASE_CRAIGSLIST_URL.format(quote_plus(search))
    print(final_url)
    
    response = requests.get(final_url)
    data = response.text
    soup = BeautifulSoup(data, features='html.parser')
    post_listings = soup.find_all('li', {'class': 'result-row'})
    
    # 存储所有帖子数据的列表
    posts = []
    for post in post_listings:
        # 获取标题(保险起见也可以加存在性判断,这里假设所有帖子都有标题)
        post_title = post.find(class_='result-title').text
        # 获取帖子链接
        post_url = post.find('a').get('href')
        # 处理价格:先检查元素是否存在,再取文本
        price_element = post.find(class_='result-price')
        post_price = price_element.text if price_element else 'No Price Listed'
        
        # 将单条帖子数据结构化后存入列表
        posts.append({
            'title': post_title,
            'url': post_url,
            'price': post_price
        })
    
    # 打印第一条帖子数据验证结果
    if posts:
        print(posts[0]['title'])
        print(posts[0]['url'])
        print(posts[0]['price'])
    
    # 传给前端的数据包含搜索关键词和所有帖子
    stuff_for_frontend = {
        'search': search,
        'posts': posts
    }
    # 修复原代码的笔误:stuff_for -> stuff_for_frontend
    return render(request, 'my_app/new_search.html', stuff_for_frontend)

关键修改说明

  • 价格安全获取:先把find的结果存到price_element变量,用三元表达式判断元素是否存在,不存在时显示自定义提示文本(比如No Price Listed),避免触发错误
  • 遍历所有帖子:不再只处理第一条帖子,而是循环所有post_listings收集数据,更符合爬取的实际需求
  • 修复拼写错误:原代码最后return里的stuff_for是笔误,改为正确的stuff_for_frontend
  • 数据结构化:用字典存储单条帖子的标题、链接、价格,再存入列表,方便前端页面遍历展示

这样修改后,既不会再触发AttributeError,也能正确获取有价格的帖子数据,没有价格的帖子会显示友好的提示文本。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 04:42:47