Python Google 搜索脚本上的 Nonetype 错误 - 这是垃圾邮件预防策略吗?

Nonetype Error on Python Google Search Script - Is this a spam prevention tactic?

对 Python 还很陌生,如果这是一个简单的问题,我们深表歉意。我浏览了其他已回答的问题,但似乎无法始终如一地运行。

我找到了下面的脚本,它打印了来自 google 的一组定义术语的最高结果。它会在我 运行 的前几次工作,但当我搜索 20 个左右的术语时会显示以下错误:

Traceback (most recent call last):
  File "term2url.py", line 28, in <module>
    results = json['responseData']['results']
TypeError: 'NoneType' object has no attribute '__getitem__'

据我所知,这表明其中一个属性没有定义值(可能是 google 阻止我的结果?)。我试图通过添加 else 子句来解决这个问题,尽管我仍然 运行 遇到同样的问题。

如有任何帮助,我们将不胜感激;我已经在下面粘贴了完整的代码。

谢谢!

#
# This is a quick and dirty script to pull the most likely url and description
# for a list of terms.  Here's how you use it:
#
# python term2url.py < {a txt file with a list of terms} > {a tab delimited file of results}
#
# You'll must install the simpljson module to use it 
#
import urllib
import urllib2
import simplejson
import sys

# Read the terms we want to convert into URL from info redirected from the command line
terms = sys.stdin.readlines()

for term in terms:

   # Define the query to pass to Google Search API
   query = urllib.urlencode({'q' : term.rstrip("\n")})
   url = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s" % (query)

   # Fetch the results and convert to JSON format
   search_results = urllib2.urlopen(url)
   json = simplejson.loads(search_results.read())

   # Process the results by pulling the first record, which has the best match
   results = json['responseData']['results']
   for r in results[:1]:
      if results is not None:
         url = r['url']
         desc = r['content'].encode('ascii', 'replace')
      else:
         url = "none"
         desc = "none"


   # Print the results to stdout.  Use redirect to capture the output
   print "%s\t%s" % (term.rstrip("\n"), url)

import time
time.sleep(1)

先为您提供一些 Python 详细信息:

None 是 Python 中的有效对象,类型为 NoneType:

print(type(None))

产生:

< class 'NoneType' >

当您尝试访问不具有该属性的对象的某些方法或属性时,您遇到的 no attribute 错误是正常的。在这种情况下,您尝试使用 __getitem__ 语法 (object[item_index]),NoneType 对象不支持这种语法,因为它没有 __getitem__ 方法。

前面解释的重点是您对错误含义的假设是正确的:您的 results 对象基本上是空的。

至于您一开始为什么会遇到这个问题,我相信您 运行 面临 Google 的 API 限制。看起来您使用的是 now deprecated 的旧 API。搜索 结果 (不是查询)的数量以前限制在每个查询 64 左右,并且过去没有费率或每天限制。但是,由于它已被弃用 5 年多了,因此可能会有新的未记录的限制。

我认为它不一定与垃圾邮件有任何关系,但我相信这是一个未记录的限制。