无法在python中使用谷歌搜索浏览api查找

时间:2015-03-31 15:38:15

标签: python google-api safe-browsing

我正在尝试将Google Safe Browsing API实现到我的python脚本中,但无法使其正常工作。代码如下所示

import urllib2
key = 'mykey'
URL = "https://sb-ssl.google.com/safebrowsing/api/lookup?client=python&apikey={key}&appver=1.0&pver=3.0&url={url}"

def is_safe(key, url):
    response = urllib2.urlopen(url).read().decode("utf8")
    return reponse != 'malware'

print(is_safe(key, 'http://google.com')) #This should return True
print(is_safe(key, 'http://steam.com.co.in')) # This should return False

当我运行代码时,对于两个查询都返回True,因为第二个URL肯定是恶意软件。

1 个答案:

答案 0 :(得分:0)

如果您使用的是python3,请尝试使用此代码。

from urllib.request import urlopen
key = "mykey"
URL = "https://sb-ssl.google.com/safebrowsing/api/lookup?client=python&apikey={key}&appver=1.0&pver=3.0&url={url}"

def is_safe(key, url):
    response = urlopen(URL.format(key=key, url=url))
    return response.read().decode("utf8") != 'malware'

print(is_safe(key, "http://www.gumblar.cn/599")) #This should return False

你犯的错误是将url传递给urlopen而不是URL。你也没有使用.format将url和key传递给URL字符串 for python 2.7

import urllib2
key = "mykey"
URL = "https://sb-ssl.google.com/safebrowsing/api/lookup?client=python&apikey={key}&appver=1.0&pver=3.0&url={url}"

def is_safe(key, url):
    response = urllib2.urlopen(URL.format(key=key, url=url))
    return response.read().decode("utf8") != 'malware'

print(is_safe(key, "http://www.gumblar.cn/599"))