I’m trying to access an API with python and I’m getting json values.
But I can’t get the values of "Variants" can someone help me with this? Thanks.
import requests
from bs4 import BeautifulSoup
import pandas as pd
import json
URL = "https://www.sonos.com/de-at/getproductpricejson?pid=sub-mini,ray,roam,roam-
sl,arc,five,sub,move,one,one-sl,beam,port,amp,boost,ceiling-speaker-pair,wall-speaker-
pair,outdoor-speaker-pair,two-room-set-roam,roam-and-wireless-charger-set,roam-sl-and-
wireless-charger-set,portable-set-move-roam,2-room-music-system-one,indoor-outdoor-set,two-
room-set-one-sl,two-room-pro-five,mounted-ray-set,beam-mount-set,arc-mount-set,two-room-set-
ray-roam,surround-set-ray-one-sl-pair,surround-set-beam-one-sl-pair,surround-set-arc-one-sl-
pair,entertainment-set-ray-sub-mini,entertainment-set-beam-sub-mini,3-1-entertainment-set-
beam-sub,entertainment-set-arc-sub,multiroom-entertainment-set-arc-and-move,immersive-set-ray-
sub-mini-one-sl,immersive-set-beam-sub-mini-one-sl,5-1-surround-set-beam-sub-one-sl,surround-
set-arc-sub-one-sl,amp-and-ceiling-set,amp-and-wall-set,amp-and-outdoor-set,vinyl-set-five-
pro-ject-t1-turntable,wall-mount-one-play1,wall-mount-one-play1-pair,shelf-one-play1,speaker-
stand-pair-one-play1,wall-hook"
r = requests.get(URL)
page = r.json()
print(page)
for element in page:
#print(element)
print(element["variants"])
I get a few results but then the error comes
print(element["variants"])
KeyError: 'variants'
2
Answers
Please try this:
The reason why you’re getting an error after a point is that there’s no variants on id:10
Hey you can just modify your code to check if a key exsits in your element like it was sayed in this issue: Check if a given key already exists in a dictionary.
When modifying your code looks like this :