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

Django项目用BeautifulSoup调用谷歌搜索报错:无法解包NoneType对象

问题解决:cannot unpack non-iterable NoneType object

错误根源

你在view.py里的google_link,google_text = google(result)行触发错误,因为google()函数返回了None,而非预期的(links, text)元组。问题出在search.py的几个逻辑错误:

  • 请求未执行:你先将r设为None,再判断if r is not None——该条件永远不成立,导致谷歌搜索请求的代码块完全未运行,函数默认返回None。
  • 返回时机错误:即便请求执行,return links, text写在for循环内部,函数拿到第一个结果就直接返回,无法收集所有结果。
  • 未处理空元素:若某个搜索结果缺少<a>或<h3>标签,直接调用a.get('href')或t.text会触发新的报错。

修正代码

修复后的search.py

import requests
from bs4 import BeautifulSoup

def google(s):
    links = []
    text = []
    USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36'
    headers = {"user-agent": USER_AGENT}
    
    try:
        # 移除错误的条件判断,直接发起搜索请求
        r = requests.get(f"https://www.google.com/search?q={s}", headers=headers)
        r.raise_for_status()  # 检查请求是否成功
        soup = BeautifulSoup(r.content, "html.parser")
        
        for g in soup.find_all('div', class_='yuRUbf'):
            a = g.find('a')
            t = g.find('h3')
            # 确保元素存在再提取数据
            if a and t:
                links.append(a.get('href'))
                text.append(t.text)
        # 循环结束后返回所有结果
        return links, text
    except Exception as e:
        # 捕获异常,返回空列表避免报错
        print(f"搜索出错: {e}")
        return [], []

优化后的view.py

def results(request):
    if request.method == "POST":
        result = request.POST.get('search', '').strip()
        # 提前处理空搜索输入
        if not result:
            return redirect('Home')
        
        google_link, google_text = google(result)
        google_data = zip(google_link, google_text)
        
        return render(request, 'results.html', {'google': google_data })

效果说明

  • 修复后的google()函数会正确发起搜索请求,收集所有有效的结果链接和标题。
  • 添加异常捕获机制,即便请求失败或解析出错,也会返回空列表,彻底避免NoneType解包错误。
  • 调整view.py逻辑,提前判断空输入,减少不必要的函数调用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 18:20:35