Get Value Of API Dictionary - python

I'm using a service with an API key and I want to print my balance.
from requests_html import HTMLSession
session = HTMLSession()
r = session.post('https://api.anycaptcha.com/getBalance', data = {'clientKey': API})
Everything works. When I do print(r.text) the following dictionary gets print:
{"errorId":0,"errorCode":"SUCCESS","balance":20.0}
However, I just want to get the value of "balance" (20.0). But I couldn't figure out how.
What I tried:
print(r.text['balance'])
# Output:
Traceback (most recent call last):
File "X/test.py", line 7, in <module>
print(r.text['balance'])
TypeError: string indices must be integers

Try this, as r.text is a string with your dict
import json
d = json.loads(r.text)
#Now you can access dict
d["balance"]

Related

'bytes' object has no attribute 'items'

While doing a CTF challenge, we are asked to enter MD5 hash of a certain 'key' within few milliseconds, so I'm trying to automate the task like this in Python3:
import re
import urllib.request
import urllib.parse
import hashlib
url = 'http://random.page'
page = urllib.request.urlopen(url)
header = {}
header['Set-Cookie'] = page.info()['Set-Cookie']
html = page.read().decode('utf-8')
key = re.search("<h3 align='center'>+.*</h3>", html).group(0)[19:-5]
md5 = hashlib.md5(key.encode()).hexdigest()
data = {'hash':md5}
post_data = urllib.parse.urlencode(data).encode('ascii')
post_header = urllib.parse.urlencode(header).encode('ascii')
request = urllib.request.Request(url, data=post_data, headers=post_header)
response = urllib.request.urlopen(request)
print(response.read().decode('utf-8'))
I want the same session as the 'key' gets changed at every request, so I'm trying to use the same cookie. But this error arises:
Traceback (most recent call last):
File "MD5.py", line 18, in <module>
request = urllib.request.Request(url, data=post_data, headers=post_header)
File "/usr/lib/python3.7/urllib/request.py", line 334, in __init__
for key, value in headers.items():
AttributeError: 'bytes' object has no attribute 'items'
Do not urlencode headers. urllib.request.Request expects it to be a dictionary.
Simply pass the headers as is and it will fix your problem.

How to print from response object

I'm currently trying to get data with python from the Internet. Fortunately the Website I want to Approach Hands me the data in json Format.
Now this is my Code:
from GetWebJson import simple_get
import json
raw_data = simple_get('http://api.openweathermap.org/data/2.5/weather?q=Hamburg,de')
raw_data.encoding
data_json = raw_data.json
print(data_json["temp"])
The simple_get function executes "Get" from the requests library and Returns the Response object.
After formatting the raw data to json In want to print the value of the key "temp". But when i debug this Code I get the following error:
Traceback (most recent call last):
File "C:\Users\nikhi\source\repos\WebScraper\WebScraper\WebScraper.py", line 7, in
print(data_json["temp"])
TypeError: 'method' object is not subscriptable
Can't I use the variable data_json like a dict? If not, how do I convert the json, which contains lists and dicts to a printable Format?

NameError in function to retrieve JSON data

I'm using python 3.6.1 and have the following code which successfully retrieves data in JSON format:
import urllib.request,json,pprint
url = "https://someurl"
response = urllib.request.urlopen(url)
data = json.loads(response.read())
pprint.pprint(data)
I want to wrap this in a function, so i can reuse it. This is what i have tried in a file called getdata.py:
from urllib.request import urlopen
import json
def get_json_data(url):
response = urlopen(url)
return json.loads(response.read())
and this is the error i get after importing the file and attempting to print out the response:
>>> import getdata
>>> print(getdata.get_json_data("https://someurl"))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\Nick\getdata.py", line 6, in get_json_data
from urllib.request import urlopen
NameError: name 'urllib' is not defined
i also tried this and got the same error:
import urllib.request,json
def get_json_data(url):
response = urllib.request.urlopen(url)
return json.loads(response.read())
What do i need to do to get this to work please?
cheers
Its working now ! I think the problem was the hydrogen addon i have for the Atom editor. I uninstalled it, tried again and it worked. Thanks for looking.

Regarding Keyerror while using Python json module

would be helped if the mistake is pointed.
Here Iam trying to create a code for displaying the name of the city state and country by taking Pincode as input, Thanks in advance
import urllib, json
from urllib.request import urlopen
from tkinter import *
global pincode
root=Tk()
frame=Frame(root,width=250,height=250)
frame.grid()
class cal:
def __init__(self):
self.string=StringVar()
entry=Entry(frame,textvariable=self.string)
entry.grid(row=1,column=2,columnspan=6)
but=Button(root,text="submit",command=self.pin)
but.grid()
def pin(self):
pincode=self.string.get()
url = "https://www.whizapi.com/api/v2/util/ui/in/indian-city-by-postal-code?pin="+pincode+"&project-app-key=fnb1agfepp41y49jz6a39upx"
response = urllib.request.urlopen(url)
data = json.loads(response.read().decode('utf8'))
fi=open("neme.txt","w")
fi.write(str(data))
state=data['State']
city=data['City']
area=data['area']
name=Label(frame,text="State:"+state+"City:"+city+"area:"+area)
name.grid(row=3,column=0)
cal()
mainloop()
error being
Traceback (most recent call last):
File "/usr/lib/python3.4/tkinter/__init__.py", line 1541, in __call__
return self.func(*args)
File "/home/yuvi/Documents/LiClipse Workspace/GUI/src/Pn_code.py", line 24, in pin
state=data['State']
KeyError: 'State'
Ok. Error tells you that you don't have key named "State" in you dict under data variable. So maybe there isn't also in incomming json.
If in response you get:
{"ResponseCode":0,"ResponseMessage":"OK","ResponseDateTime":‌​"9/3/2016 2:41:25 PM GMT","Data":[{"Pincode":"560103","Address":"nagar","City":"B‌​analore","State":"na‌​taka","Country":"Ind‌​ia"}]}
then you cannot get "State" by using:
data["State"]
you have to do it using:
data["Data"][0]["State"]
and the rest:
data["Data"][0]["City"]
data["Data"][0]["Country"]
Why in this way? Because you have to get nested keys, first key is "Data", using data["Data"] you recieve a list, and because it's one element list, you have to get first item of the list: data["Data"][0]. And at the end under data["Data"][0] you get dict of keys where you can find State, City, Country.

Nonetype object has no attribute '__getitem__'

I am trying to use an API wrapper downloaded from the net to get results from the new azure Bing API. I'm trying to implement it as per the instructions but getting the runtime error:
Traceback (most recent call last):
File "bingwrapper.py", line 4, in <module>
bingsearch.request("affirmative action")
File "/usr/local/lib/python2.7/dist-packages/bingsearch-0.1-py2.7.egg/bingsearch.py", line 8, in request
return r.json['d']['results']
TypeError: 'NoneType' object has no attribute '__getitem__'
This is the wrapper code:
import requests
URL = 'https://api.datamarket.azure.com/Data.ashx/Bing/SearchWeb/Web?Query=%(query)s&$top=50&$format=json'
API_KEY = 'SECRET_API_KEY'
def request(query, **params):
r = requests.get(URL % {'query': query}, auth=('', API_KEY))
return r.json['d']['results']
The instructions are:
>>> import bingsearch
>>> bingsearch.API_KEY='Your-Api-Key-Here'
>>> r = bingsearch.request("Python Software Foundation")
>>> r.status_code
200
>>> r[0]['Description']
u'Python Software Foundation Home Page. The mission of the Python Software Foundation is to promote, protect, and advance the Python programming language, and to ...'
>>> r[0]['Url']
u'http://www.python.org/psf/
This is my code that uses the wrapper (as per the instructions):
import bingsearch
bingsearch.API_KEY='abcdefghijklmnopqrstuv'
r = bingsearch.request("affirmative+action")
I tested this out myself, and it seems what you are missing is to properly url-encode your query. Without it, I was getting a 400 code.
import urllib2
import requests
# note the single quotes surrounding the query
URL = "https://api.datamarket.azure.com/Data.ashx/Bing/SearchWeb/Web?Query='%(query)s'&$top=50&$format=json"
query = 'affirmative+action'
# query == 'affirmative%2Baction'
r = requests.get(URL % {'query': urllib2.quote(query)}, auth=('', API_KEY))
print r.json['d']['results']
Your example doesn't make much sense because your request wrapper returns a list of results, yet in your main usage example you are calling it and then checking a status_code attribute on the return value (which is the list). That attribute would be present on the response objects, but you don't return it from your wrapper.

Categories