pythonpython-3.xsafe-browsing

Google SafeBrowsing API: always getting an error


I use google safe browsing API. So I tested this simple code:

from safebrowsinglookup import SafebrowsinglookupClient

class TestMe:
    def testMe(self):
        self.key='my_Valid_Key_Here'        
        self.client=SafebrowsinglookupClient(self.key)
        self.response=self.client.lookup('http://www.google.com')
        print(self.response)

if __name__=="__main__":
    TM=TestMe()
    TM.testMe()

I always get this whatever the website I test:

{'website_I_tried','error'}

Note that I had to change some lines in the source code after I installed this API because it was written in Python 2 and I am using Python 3.4.1. How can I resolve this problem?


Update:

To understand why the above problem occured to me, I run this code:

from safebrowsinglookup import SafebrowsinglookupClient  

class TestMe:
    def testMe(self):
        self.key = 'my_key_here'        
        self.client=SafebrowsinglookupClient(self.key,debug=1)
        urls = ['http://www.google.com/','http://addonrock.ru/Debugger.js/']        
        self.results = self.client.lookup(*urls)
        print(self.results['http://www.google.com/'])

if __name__ == "__main__":
    TM=TestMe()
    TM.testMe()

Now, I got this message:

BODY:
2
http://www.google.com/
http://addonrock.ru/Debugger.js/


URL: https://sb-ssl.google.com/safebrowsing/api/lookup?client=python&apikey=ABQIAAAAAU6Oj8JFgQpt0AXtnVwBYxQYl9AeQCxMD6irIIDtWpux_GHGQQ&appver=0.1&pver=3.0
Unexpected server response

name 'urllib2' is not defined
error
error

Solution

  • The library doesn't support Python3.x.

    In this case, you can either make it support Python3 (there is also an opened pull request for Python3 Compatibility), or make the request to "Google Safebrowsing API" manually.

    Here's an example using requests:

    import requests
    
    key = 'your key here'
    URL = "https://sb-ssl.google.com/safebrowsing/api/lookup?client=api&apikey={key}&appver=1.0&pver=3.0&url={url}"
    
    
    def is_safe(key, url):
        response = requests.get(URL.format(key=key, url=url))
        return response.text != 'malware'
    
    
    print(is_safe(key, 'http://addonrock.ru/Debugger.js/'))  # prints False
    print(is_safe(key, 'http://google.com'))  # prints True
    

    Just the same, but without third-party packages (using urllib.request):

    from urllib.request import urlopen
    
    
    key = 'your key here'
    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)).read().decode("utf8")
        return response != 'malware'
    
    
    print(is_safe(key, 'http://addonrock.ru/Debugger.js/'))  # prints False
    print(is_safe(key, 'http://google.com'))  # prints True