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

Win11正常的谷歌搜索Python代码在Linux Mint中报TypeError求助

问题分析与修复方案

报错原因

googlesearch库的search()函数返回的是生成器对象,生成器属于迭代器的一种,不支持像列表那样的切片操作([:num_results])。你在Win11上能正常运行,大概率是因为该环境下安装的库版本返回的是列表而非生成器;而Linux Mint环境的库版本返回生成器,直接切片就触发了TypeError。

修复方案

有两种可行的修复方式:

方式1:将生成器转为列表

把生成器转换成列表后,就可以正常使用切片操作了,代码修改如下:

from googlesearch import search
import webbrowser, sys
import time

searching_for = input("Input search words: ")

num_results = int(input("How many results : ") or "3")

# 将生成器转为列表
result = list(search(searching_for))

for i in result[:num_results]:
    webbrowser.open(i)
    time.sleep(1)

方式2:使用itertools.islice截取生成器元素

如果不想一次性把所有结果加载到内存(适合结果较多的场景),可以用itertools.islice直接从生成器中截取前N个元素:

from googlesearch import search
import webbrowser, sys
import time
from itertools import islice

searching_for = input("Input search words: ")

num_results = int(input("How many results : ") or "3")

result = search(searching_for)

# 用islice截取前num_results个元素
for i in islice(result, num_results):
    webbrowser.open(i)
    time.sleep(1)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 04:07:34