Reputation:
I want to access a specific element with python, but I can't
import json
import requests
search_book = str(input("search a book: "))
request = requests.get("https://www.googleapis.com/books/v1/volumes?q=" + search_book)
request_text = request.text
data = request_text
print(data['items']['volumeInfo']['title'])
the mistake is:
Traceback (most recent call last): File "C:/Users/ddvit/Documents/programming/python/books/books.py", line 9, in print(data['items']['volumeInfo']['title']) TypeError: string indices must be integers
Thank you very much in advance :)
Upvotes: 1
Views: 1498
Reputation: 1837
You taking raw text from response, use json()
method instead:
import json
import requests
search_book = str(input("search a book: "))
response = requests.get("https://www.googleapis.com/books/v1/volumes?q=" + search_book)
data = response.json()
Upvotes: 1
Reputation: 54148
To get the rseult as JSON you need to either load it json.loads(request.text)
or retrieve directly with request.json()
Then items is an array, so you can't access the info directly,
you may iterate on it, then get the title
data = request.json()
for item in data['items']:
title = item['volumeInfo']['title']
print(title)
access one directly
print(data['items'][0]['volumeInfo']['title'])
Upvotes: 1