简体   繁体   中英

Can't fetch data from python request response

I'm new to Python, I'm using "requests" to send a post request in api endpoint and the response I get like this:

{"success":true,"data":4503615,"message":"Thanks","lid":""}

and my code like this :

    import requests

para1 = {'username': 'xxxx' ,'password': 'xxx'} 
req1 = requests.post('https://testpy.com/login', data = para1)
print(req1) 

the response I got is similar to dictionary type except the "success":true , I just want that "data":4503615 numbers in a new variable. I tried to fetch that like this

import requests

    para1 = {'username': 'xxxx' ,'password': 'xxx'} 
    req1 = requests.post('https://testpy.com/login', data = para1)
    qq = req1.text
    cc = qq["data"]
    print(cc)

But it didn't show the number, Is there any way to get that number? Thanks

Use req1.json() instead of req1.text , it parses the text of the response to a dictionary you can use in the way you describe above.

So replace

qq = req1.text

with

qq = req1.json()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM