I am trying to get all IPv4 addresses from the goog.json file (https://www.gstatic.com/ipranges/goog.json) into a list in Python. This is what I am writing
import json
import requests
ip_ranges_google = requests.get('https://www.gstatic.com/ipranges/goog.json').json()['prefixes']
google_ips = [item['ipv4Prefix'] for item in ip_ranges_google]
What I get back is
Traceback (most recent call last):
File "c:\Soumik Work\Code\get_google_ips.py", line 6, in <module>
google_ips = [item['ipv4Prefix'] for item in ip_ranges_google]
File "c:\Soumik Work\Code\get_google_ips.py", line 6, in <listcomp>
google_ips = [item['ipv4Prefix'] for item in ip_ranges_google]
KeyError: 'ipv4Prefix'
What am I doing wrong? I am a total newbie to Python, so a little help please?
CodePudding user response:
Some items don't contain key ipv4Prefix
, but only ipv6Prefix
. To get only items with ipv4Prefix
you can do:
import json
import requests
ip_ranges_google = requests.get(
"https://www.gstatic.com/ipranges/goog.json"
).json()["prefixes"]
google_ips = [
item["ipv4Prefix"] for item in ip_ranges_google if "ipv4Prefix" in item
]
print(*google_ips, sep="\n")
Prints:
...
208.68.108.0/22
208.81.188.0/22
208.117.224.0/19
209.85.128.0/17
216.58.192.0/19
216.73.80.0/20
216.239.32.0/19
CodePudding user response:
Your error is because there is some dicts that does not have "ipv4Prefix". Some of them say "ipv6Prefix"
Insert a try except to catch your error so that it doesn't break.
import requests
ip_ranges_google = requests.get('https://www.gstatic.com/ipranges/goog.json').json()['prefixes']
google_ips = []
for item in ip_ranges_google:
try:
google_ips.append(item['ipv4Prefix'])
except KeyError:
pass
print(google_ips)