Python谷歌搜索脚本上的非类型错误-这是一种垃圾邮件预防策略吗



对于Python来说,这是一个相当陌生的问题,所以如果这只是一个简单的问题,我很抱歉。我浏览了其他已回答的问题,但似乎无法使其持续运行。

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

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

据我所知,这表明其中一个属性没有定义的值(可能是谷歌屏蔽我的结果?)。我试图通过添加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 "%st%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对象基本上是空的。

至于你为什么一开始就这么做,我相信你已经达到了谷歌API的限制。看起来您使用的是旧的API,现在已被弃用。搜索结果(非查询)的数量过去限制在每个查询64个左右,并且过去没有费率或每天限制。然而,由于它已经被否决了5年多,可能会有新的无证限制。

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

最新更新