I am trying to get the URL of an image to download it by command line from a jsonp pixabay answer (using its API):
This is the request:
import jsonp2json
import json
import python_pixabay
pix = python_pixabay.Pixabay('xxxxxx')
# default image search
img_search = pix.image_search()
# custom image search
jsonp_response = pix.image_search(q = 'cats dogs',
lang = 'es',
response_group = 'high_resolution',
image_type = 'photo',
orientation = 'horizontal',
category = 'animals',
safesearch = 'true',
order = 'latest',
page = 1,
per_page = 3)
print(jsonp_response)
The answer 'jsonp_response' comes in jsonp format, like this:
{
'totalHits': 156,
'hits': [
{
'largeImageURL': 'https://pixabay.com/get/....jpg',
'webformatHeight': 360,
'webformatWidth': 640,
'likes': 2,
'imageWidth': 5184,
'id': 3396156,
'user_id': 8982455,
'views': 280,
'comments': 0,
'pageURL': 'https://pixabay.com/es/gato-mascota-animales-blanco-3396156/',
'imageHeight': 2916,
'webformatURL': 'https://pixabay.com/get/....jpg',
'type': 'photo',
'previewHeight': 84,
'tags': 'gato, mascota, animales',
'downloads': 126,
'user': 'mohdrashidsmc',
'favorites': 2,
'imageSize': 974885,
'previewWidth': 150,
'userImageURL': '',
'previewURL': 'https://cdn.pixabay.com/photo/2018/05/13/11/40/cat-3396156_150.jpg'
},
.....
.....
.....
] , 'total': 156}
Actually there are several of these in the same answer but I have only put one here so it is not so extensive.
I'm also using a module called 'jsonp2json' and it only includes this function.
import sys
def convert(jsonp):
try:
l_index = jsonp.index('(') + 1
r_index = jsonp.rindex(')')
except ValueError:
print("Input is not in a jsonp format.")
return
res = jsonp[l_index:r_index]
return res
And I'm trying to do this to get the data in json
json_result = jsonp2json.convert(jsonp_response)
result = json.loads(json_result)
print(result)
And I'm getting this error: - (
$ py -3 c:/Users/ivan/Desktop/pixabay/get_img.py Traceback (most recent call last):
File "c:/Users/ivan/Desktop/pixabay/get_img.py", line 30, in <module>
json_result = jsonp2json.convert(jsonp_response)
File "c:/Users/ivan/Desktop/pixabay/get_img.py", line 7, in convert
l_index = jsonp.index('(') + 1
AttributeError: 'dict' object has no attribute 'index
Pes, I'm not sure if the problem is in the variable jsonp_response or in the function convert (jsonp) Any idea how to solve this? p>
Ideally, do something like this:
print(json_result['largeImageURL'][0])
print(json_result['largeImageURL'][1])
print(json_result['largeImageURL'][2])
and get an exit like this
'https://pixabay.com/get/0.jpg'
'https://pixabay.com/get/1.jpg'
'https://pixabay.com/get/2.jpg'