从获取请求的响应中解析并获取列表 [英] parsing and getting list from response of get request
本文介绍了从获取请求的响应中解析并获取列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用请求模块解析网站:
I'm trying to parse a website with the requests module:
import requests
some_data = {'a':'',
'b':''}
with requests.Session() as s:
result = s.post('http://website.com',data=some_data)
print(result.text)
页面的响应如下:
{
"arrangetype":"U",
"list": [
{
"product_no":43,
"display_order":4,
"is_selling":"T",
"product_empty":"F",
"fix_position":null,
"is_auto_sort":false
},
{
"product_no":44,
"display_order":6,
"is_selling":"T",
"product_empty":"F",
"fix_position":null,
"is_auto_sort":false
}
],
"length":2
}
我发现与其解析完整的HTML,不如处理响应,因为我想要的所有数据都在该响应中.
I found that instead of parsing full HTML, it would be better to deal with the response as all the data I want is in that response.
我想要得到的是product_no
值的列表,所以预期结果是:
What I want to get is a list of the values of product_no
, so the expected result is:
[43,44]
我该怎么做?
推荐答案
使用 json.loads()
,然后以列表理解的方式收集结果.
Convert your JSON response to a dictionary with json.loads()
, and collect your results in a list comprehension.
演示:
from json import loads
data = """{
"arrangetype":"U",
"list": [
{
"product_no":43,
"display_order":4,
"is_selling":"T",
"product_empty":"F",
"fix_position":null,
"is_auto_sort":false
},
{
"product_no":44,
"display_order":6,
"is_selling":"T",
"product_empty":"F",
"fix_position":null,
"is_auto_sort":false
}
],
"length":2
}"""
json_dict = loads(data)
print([x['product_no'] for x in json_dict['list']])
# [43, 44]
完整代码:
import requests
from json import loads
some_data = {'a':'',
'b':''}
with requests.Session() as s:
result = s.post('http://website.com',data=some_data)
json_dict = loads(result.text)
print([x["product_no"] for x in json_dict["list"]])
这篇关于从获取请求的响应中解析并获取列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文