【问题标题】:Python TypeError: 'NoneType' object has no attribute '__getitem__' for Google SearchPython TypeError:“NoneType”对象没有用于 Google 搜索的属性“__getitem__”
【发布时间】:2014-04-05 03:17:59
【问题描述】:

我有一份人员和公司列表,我正在尝试搜索 Google 以找出这些人的链接网址。

我的代码:

#!/usr/bin/python3
import json
import urllib2
import time

file = open('names_and_companies.txt', 'r')
lines =file.readlines()
file.close()

file_out = open('out-urls.txt', 'w')

for line in lines:
    line = line.strip()
    lst = line.split(",")
    search_term = lst[0] + " " + lst[1] #construct a search term using name and company
    search_term = search_term.replace(" ","+")

    time.sleep(1)
    encoded = urllib2.quote(search_term)
    rawData = urllib2.urlopen ('http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q='+encoded).read()

    jsonData = json.loads(rawData)
    print "\n\n\n" + search_term + "\n\n\n"


    searchResults = jsonData['responseData']['results']
    print searchResults

    for er in searchResults:
        link = er['url']
        if "www.linkedin.com" in link:
            print link
            file_out.write(lst[0] + " | " + lst[1] + " | " + link + "\n")

file_out.close()

当我运行它时,我收到以下错误:

Traceback(最近一次调用最后一次): 文件“/Users/InNov8/Desktop/conference/delete.py”,第 30 行,在 searchResults = jsonData['responseData']['results'] TypeError:“NoneType”对象没有属性“getitem

我知道这个主题之前已经讨论过,但是我是菜鸟,不知道如何将任何推荐的修复应用到我的特定代码中。

谢谢。

【问题讨论】:

  • 试试print(jsonData['responseData'])。看看它写了什么。

标签: python


【解决方案1】:

jsonData['responseData'] 返回 None,所以你不能索引它 (jsonData['responseData']['results'])

一种可能的解决方法是检查 jsonData['responseData'] 是否为 None:

responseData = jsonData['responseData']
if responseData is not None: 
    searchResults = responseData['results']
    print searchResults

    for er in searchResults:
        link = er['url']
        if "www.linkedin.com" in link:
            print link
            file_out.write(lst[0] + " | " + lst[1] + " | " + link + "\n")

【讨论】:

    猜你喜欢
    • 2018-04-13
    • 2013-04-15
    • 1970-01-01
    • 2017-01-08
    • 2017-08-17
    • 2012-12-04
    • 2014-07-03
    • 1970-01-01
    相关资源
    最近更新 更多