0

我正在尝试在我的 python 脚本中实现 Google 安全浏览 API,但无法使其正常工作。代码如下所示

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 肯定是恶意软件。

4

1 回答 1

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 和密钥传递给 python 2.7 的 URL 字符串

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")) 
于 2015-03-31T18:50:45.550 回答