记录python爬某文化交易遇到的问题xml转json读出单个数据

2023-08-08 13:54:41 浏览数 (1)

爬到的数据

代码语言:javascript复制
<?xml version="1.0" encoding = "GBK"?><MEBS_MOBILE><REP name="hqjmc"><RESULT><JMC>89735167965775242892794118565310060813624119753161464612935749255847023178783461074917353297446270619254464435182697497003837752615791825176330069793843733964958426483172450032907003159612282417328917867514472938219197310751053269455659166240174428725524508884553123031959307889945926696379527035467155749000</JMC><RETCODE>0</RETCODE><MESSAGE></MESSAGE></RESULT></REP></MEBS_MOBILE>
<?xml version="1.0" encoding = "GBK"?><MEBS_MOBILE><REP name="user_login"><RESULT><MODULE_ID>7</MODULE_ID><LAST_TIME>2022-03-22 15:45:38</LAST_TIME><LAST_IP>14.205.91.113</LAST_IP><CHG_PWD>0</CHG_PWD><NAME>136639900251</NAME><RANDOM_KEY>2022032215461159613663990025194294</RANDOM_KEY><U>136639900251</U><BID>1366399</BID><PHONE>13213107881</PHONE><IS_USDT>0</IS_USDT><RETCODE>3501315678706488957</RETCODE></RESULT></REP></MEBS_MOBILE>
<?xml version="1.0" encoding = "GBK"?><MEBS_MOBILE><REP name="check_user"><RESULT><MODULE_ID>7</MODULE_ID><RETCODE>3495802602732227245</RETCODE></RESULT></REP></MEBS_MOBILE>
<?xml version="1.0" encoding = "GBK"?><MEBS_MOBILE><REP name="firm_info"><RESULT><FI>136639900251</FI><FN>黄木钦</FN><TP>-1</TP><IF>3099.08</IF><IN_F>0</IN_F><OU_F>0</OU_F><HK_S>0</HK_S><IC>0</IC><UC>0</UC><HK_B>3043.7</HK_B><OR_F>0</OR_F><OT_F>0.00</OT_F><IS>0</IS><FEE>4.42</FEE><BC_R>0</BC_R><BC_U>0</BC_U><BC_C>0</BC_C><BC_D>0</BC_D><SAF>0</SAF><OC>0.00</OC><MV>4603.68</MV><SG_F>0</SG_F><UF>50.96</UF><DQ>50.96</DQ><JYSQY>4654.64</JYSQY><IN_OUT>-100.0</IN_OUT><S_P_A_L>0.0</S_P_A_L><LISTING_F>0</LISTING_F><OVERDUE_FINE>0</OVERDUE_FINE><H_P_A_L>1562.869989</H_P_A_L><RETCODE>0</RETCODE><MESSAGE></MESSAGE></RESULT></REP></MEBS_MOBILE>

需要解析成json格式

代码语言:javascript复制
import json
import xmltodict

b = """<?xml version="1.0" encoding = "GBK"?><MEBS_MOBILE><REP name="hqjmc"><RESULT><JMC>89735167965775242892794118565310060813624119753161464612935749255847023178783461074917353297446270619254464435182697497003837752615791825176330069793843733964958426483172450032907003159612282417328917867514472938219197310751053269455659166240174428725524508884553123031959307889945926696379527035467155749000</JMC><RETCODE>0</RETCODE><MESSAGE></MESSAGE></RESULT></REP></MEBS_MOBILE>"""


# 定义xml转json的函数
def xml_to_json(xml_str):
    # parse是的xml解析器
    xml_parse = xmltodict.parse(xml_str)
    # json库dumps()是将dict转化成json格式,loads()是将json转化成dict格式。
    # dumps()方法的ident=1,格式化json
    json_str = json.dumps(xml_parse, indent=1)
    aa=json.loads(json_str)
    return aa
a=xml_to_json(b)
print(a)
print("=============")
print(a['MEBS_MOBILE'])
print("=============")
print(type(a))

完结撒花!!!

0 人点赞