Уведомления

Группа в Telegram: @pythonsu

#1 Апрель 24, 2015 08:55:31

Moi5es
Зарегистрирован: 2014-10-15
Сообщения: 65
Репутация: +  0  -
Профиль   Отправить e-mail  

Google API - TypeError: 'NoneType' object is not subscriptable

Есть скрипт 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 (Апрель 24, 2015 09:29:29)

Офлайн

#2 Апрель 24, 2015 08:57:34

Moi5es
Зарегистрирован: 2014-10-15
Сообщения: 65
Репутация: +  0  -
Профиль   Отправить e-mail  

Google API - TypeError: 'NoneType' object is not subscriptable

содержимое search.txt

inurl:/index.html
inurl:/index.php

Офлайн

#3 Апрель 24, 2015 09:42:44

ayb
Зарегистрирован: 2014-04-01
Сообщения: 297
Репутация: +  24  -
Профиль   Отправить e-mail  

Google API - TypeError: 'NoneType' object is not subscriptable

У тебя приходит 400 ответ. А там нет элемента results. Пропустил параметр q в запросе.
Поправь.

 url = ('http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=%s' % query)

Отредактировано ayb (Апрель 24, 2015 09:48:23)

Офлайн

#4 Апрель 24, 2015 09:43:36

terabayt
От: Киев
Зарегистрирован: 2011-11-26
Сообщения: 1099
Репутация: +  103  -
Профиль   Отправить e-mail  

Google API - TypeError: 'NoneType' object is not subscriptable

>>> 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:



————————————————
-*- Simple is better than complex -*-

Офлайн

#5 Апрель 24, 2015 10:59:00

Moi5es
Зарегистрирован: 2014-10-15
Сообщения: 65
Репутация: +  0  -
Профиль   Отправить e-mail  

Google API - TypeError: 'NoneType' object is not subscriptable

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

Отредактировано Moi5es (Апрель 24, 2015 10:59:46)

Офлайн

#6 Апрель 24, 2015 11:33:39

sander
Зарегистрирован: 2015-02-19
Сообщения: 317
Репутация: +  53  -
Профиль   Отправить e-mail  

Google API - TypeError: 'NoneType' object is not subscriptable

Moi5es
в запросе не все верно если

'responseStatus': 403

Офлайн

#7 Апрель 24, 2015 11:53:04

Moi5es
Зарегистрирован: 2014-10-15
Сообщения: 65
Репутация: +  0  -
Профиль   Отправить e-mail  

Google API - TypeError: 'NoneType' object is not subscriptable

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)

Отредактировано Moi5es (Апрель 24, 2015 11:54:10)

Офлайн

#8 Апрель 24, 2015 11:55:42

ayb
Зарегистрирован: 2014-04-01
Сообщения: 297
Репутация: +  24  -
Профиль   Отправить e-mail  

Google API - TypeError: 'NoneType' object is not subscriptable

В запросе всё верно. Если в код вставить строчку

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

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}


Рекомендую почитать

Отредактировано ayb (Апрель 24, 2015 11:58:07)

Офлайн

#9 Апрель 24, 2015 12:02:02

Moi5es
Зарегистрирован: 2014-10-15
Сообщения: 65
Репутация: +  0  -
Профиль   Отправить e-mail  

Google API - TypeError: 'NoneType' object is not subscriptable

ayb
А ты не пробовал читать ?
см. комментарий выше

Офлайн

#10 Апрель 24, 2015 12:11:22

ayb
Зарегистрирован: 2014-04-01
Сообщения: 297
Репутация: +  24  -
Профиль   Отправить e-mail  

Google API - TypeError: 'NoneType' object is not subscriptable

Из вики ( как в 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
>>>

Офлайн

Board footer

Модераторировать

Powered by DjangoBB

Lo-Fi Version