Here's the basic request:
req = urllib2.Request(f"https://www.voter.ie/api/search/name/{name}/surname/{surname}/eircode/{eircode}/lang/en")
req.add_header("Connection", "keep-alive")
req.add_header("Accept", "application/json, text/plain, */*")
req.add_header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36 OPR/62.0.3331.99")
req.add_header("Accept-Encoding", "gzip, deflate, br")
req.add_header("Accept-Language", "en-US,en;q=0.9")
response = urllib2.urlopen(req)
Here are the headers, I can see that it's JSON in Content-Type and encoding is utf-8:
response.getheaders()
[('Transfer-Encoding', 'chunked'),
('Content-Type', 'application/json; charset=utf-8'),
('Content-Encoding', 'gzip'),
('Vary', 'Accept-Encoding'),
('Server', 'Kestrel'),
('Request-Context', 'appId=cid-v1:25017a8d-4490-471a-a8d0-e9e17860f987'),
('Strict-Transport-Security', 'max-age=2592000'),
('X-Content-Type-Options', 'nosniff'),
('Referrer-Policy', 'no-referrer'),
('X-XSS-Protection', '1; mode=block'),
('X-Frame-Options', 'Deny'),
('X-Powered-By', 'ASP.NET'),
('Date', 'Fri, 02 Aug 2019 14:45:33 GMT'),
('Connection', 'close')]
So when I try to read it or decode it I am getting many errors, but first of all this is what it looks like. I haven't posted the full string as it's too long, but this is a sample:
response.read()
b'\x1f\x8b\x08\x00\x00\x00\x00\x00\x04\x00\xed\xbd\x07`\x1cI\x96%&/m\xca{\x7fJ\xf5J\xd7\xe0t\xa1\x08\x80`\x13$\xd8\x90@\x10\xec\xc1\x88\xcd\xe6\x92\xec\x1diG#)\xab*\x81\xcaeVe]f\x16@\xcc\xed\x9d\xbc\xf7\xde{\xef\xbd\xf7\xde{\xef\xbd\xf7\xba;\x9dN\'\xf7\xdf\xff?\\fd\x01l\xf6\xceJ\xda\xc9\x9e!\x80\xa
What I've tried using methods I've found on here StackOverflow:
response.read().decode('utf-8')
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte
raw_data = response.read()
json.loads(raw_data.decode('utf-8'))
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte
string = response.read().decode('utf-8')
json_obj = json.loads(string)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte
What am I doing wrong?
As the response headers hint, the data has been compressed with gzip. You need to decompress it before doing anything else.
import gzip, json
gz = response.read()
j = gzip.decompress(gz)
data = json.loads(j.decode('utf-8'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With