POST参数转为DICT

POST参数转为DICT

  • 一、需求说明
  • 二、我的解决方案
  • 写在最后

一、需求说明

当我们使用requests库编写爬虫时,往往需要抓包分析其中的POST请求参数,然后再将其转为DICT类型。当我看到参数是这样时:

dopost=login&userid=admin&pwd=admin

我心中不由笑开了花:这么简单,何必如此大费周章?对应的DICT不就是这样么:

{
 'dopost':'login',
 'userid':'admin',
 'pwd':'admin'
}

小明同学,专制各种不服!!!这位嚣张的同学,请听题:

orderType=-1&receUserInfo={"receUserName":"xxx","receUserCardCode":"xxxxxxxxxxxxxxxxxx","receUserCardCodeType":"1","receUserContact":"xxxxxxxxxxx"}&orderInfo=[{"supplierId":"3601","stationMapId":"7301908","endId":"10720428","endTypeId":"1","planId":"2020-04-07%2C07%3A50%2CX0518%2C430923019%2C430103","planDate":"2020-04-07","driveTime":"07:50","arMoney":86,"orderModelId":"1","goBackFlag":"1","orderCount":1,"ticketOrderMoneyInfo":{"orderMoney":76,"feeMoney":4,"yhqVo":{"yhqId":"","yhqMoney":""},"actionInfo":{"reduceActionCode":"","reduceMoney":0}},"insureOrderMoneyInfo":{"orderMoney":10,"inspackInfo":{"inspackId":602,"inspackReduceMoney":2}},"ticketInfo":[{"ticketTypeId":"1","userCadeType":"1","userCardCode":"xxxxxxxxxxxxxxxxxx","userCardName":"xxx","birthday":"1996-08-24","saveUserFlag":"Y","chooseInspackFlag":"Y","premiumInfo":[],"childInfo":{},"userMobile":"xxxxxxxxxxx"}],"discountInfo":{"cbFlag":"N","cbMoney":0,"intAmount":0}}]&schInfo=[{"ticketTypeList":[{"name":"全","price":"76","id":"1"}],"seats":"48","seatAmount":"42","drvTime":"07:50","schCanSellFlag":"1"}]&t=D3EDDEAF8D7C43B9A94C722982B71ED0

emmmm…对不起,打扰了,溜了遛了。

二、我的解决方案

要是我一个一个去打出来,也许情怀是允许的,可是发量可不答应,于是我想了个办法:

# =============================================================================
# POST请求参数转dict
# =============================================================================
import json

post = '' # 这里是请求包里的POST参数
post_list = post.split('&') # 把参数转为list
data = {}
for p in post_list:
    try:
        data[p.split('=')[0]] = json.loads(p.split('=')[1]) # 如果参数里含有字典等
    except:
        data[p.split('=')[0]] = p.split('=')[1] # 如果不含
print(data)


其实就是对字符串的处理,并通过json库来进一步处理。(因为某些参数可能本身包含字典、列表等类型)

写在最后

感谢各位大大的阅读~

你可能感兴趣的:(POST参数转为DICT)