我正在尝试将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肯定是恶意软件。
如果您使用的是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和关键字传递到url字符串对于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"))