Найти - Пользователи
Полная версия: Google API - TypeError: 'NoneType' object is not subscriptable
Начало » Python для новичков » Google API - TypeError: 'NoneType' object is not subscriptable
1 2 3
Moi5es
Есть скрипт test.py:
# -*- coding: utf-8 -*-
import json, requests, sys, time, urllib.request, urllib.parse
def title():
	print ("\n\t Test script ")
	print ("\t---------------\n")
	
def usage():
	title()
	print ("\n  Usage: python test.py <domain/ip> <searchlist>\n")
def timer():
	now = time.localtime(time.time())
	return time.asctime(now)
if len(sys.argv) <= 2:
	usage()
	sys.exit(1)
else:
	title()
domain = "site:" + sys.argv[1]
file_name = sys.argv[2]
def showsome(domain):
        fopen = open(file_name, 'r')
        counter = 0
        for x in fopen.readlines():
                counter = counter + 1
                google_search = domain + " " + x.strip('\n')
                query = urllib.parse.urlencode({'q': google_search})
                url = ('http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s' % query)
                search_response = urllib.request.urlopen(url)
                search_results = search_response.read().decode("utf-8")
                results = json.loads(search_results)
                data = (results['responseData'])
                if len(data['results']) > 0:
                        print('Total results: %s' % data["cursor"]["estimatedResultCount"])
                        hits = (data['results'])
                        print ('Top %d hits:' % len(hits))
                        for h in hits:
                                print ('[+]', h['url'])
                        #print ('For more results, see %s' % data["cursor"]["moreResultsUrl"])
        fopen.close()
showsome(domain)

Если его запустить, он выдает ошибку:
C:\Users\User>python C:\test.py example.com "C:\search.txt"
Traceback (most recent call last):
  File "C:\test.py", line 52, in <module>
    showsome(domain)
  File "C:\test.py", line 44, in showsome
    if len(data['results']) > 0:
TypeError: 'NoneType' object is not subscriptable

В гугле ответ найти не получилось.
Что я делаю не так?
Moi5es
содержимое search.txt
inurl:/index.html
inurl:/index.php
ayb
У тебя приходит 400 ответ. А там нет элемента results. Пропустил параметр q в запросе.
Поправь.

 url = ('http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=%s' % query)
terabayt
>>> a = None
>>> a['bad']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not subscriptable
это говорит о том что results равно None

не вникая в логику программы можно проверять results
if data['results'] and len(data['results']) > 0:
Moi5es
ayb
У тебя приходит 400 ответ. А там нет элемента results. Пропустил параметр q в запросе.Поправь.
В запросе всё верно. Если в код вставить строчку
print(results)
будет видна ошибка:
{'responseDetails': 'Suspected Terms of Service Abuse. Please see http://code.go
ogle.com/apis/errors', 'responseStatus': 403, 'responseData': None}
...

terabayt
if data and len(data) > 0:
Тоже самое
Traceback (most recent call last):
  File "C:\test.py", line 52, in <module>
    showsome(domain)
  File "C:\test.py", line 44, in showsome
    if data['results'] and len(data['results']) > 0:
TypeError: 'NoneType' object is not subscriptable
sander
Moi5es
в запросе не все верно если
'responseStatus': 403
Moi5es
sander
q=
Я имел ввиду, ошибка возникает, если добавить “q=”

“q=” в моем случае
query = urllib.parse.urlencode({'q': google_search})
url = ('http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s' % query)
ayb
В запросе всё верно. Если в код вставить строчку

А ты не пробовал читать ?

ayb@aybb:~$ curl 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&example.com'
{“responseData”: null, “responseDetails”: "missing query parameter ‘q’“, ”responseStatus": 400}

ayb@aybb:~$ curl 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=example.com'
{“responseData”: {“results”:,“cursor”:{“resultCount”:“177,000,000”,“pages”:,“estimatedResultCount”:“177000000”,“currentPageIndex”:0,“moreResultsUrl”:"http://www.google.com/search?oe\u003dutf8\u0026ie\u003dutf8\u0026source\u003duds\u0026start\u003d0\u0026hl\u003den\u0026q\u003dexample.com“,”searchResultTime“:”0.35“}}, ”responseDetails“: null, ”responseStatus": 200}


Рекомендую почитать
Moi5es
ayb
А ты не пробовал читать ?
см. комментарий выше
ayb
Из вики ( как в URL передавать параметры запроса ):

?параметр_1=значение_1&параметр_2=значение_2&параметр3=значение_3

Ну и чтобы ты убедился :

>>> import requests
>>> query = 'URL'
>>> request = requests.get('http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=%s' % query)
>>> for result in request.json()['responseData']['results']:
... print(result['url'])
...
http://en.wikipedia.org/wiki/Uniform_resource_locator
http://www.webopedia.com/TERM/U/URL.html
https://goo.gl/
http://docs.oracle.com/javase/7/docs/api/java/net/URL.html
>>>
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB