pythongoogle-apisafe-browsing

Unable to use google search browsing api lookup in python


I am trying to implement Google Safe Browsing API into my python script but cannot get it to work properly. Code shown below

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

When I ran the code, it returned True for both queries which shouldn't because the second URL is definitely malware.


Solution

  • Try this code if you are using 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
    

    The mistake you are making is passing url to urlopen instead of URL.Also you are not using using .format to pass url and key to the URL string 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"))