从python输出中获取文本的方法

2024-10-08 19:22:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python的新手,编写一个脚本,对服务器执行soap请求并给我会话id

import requests
import re

endpoint = "http://192.168.66.2:10101/IntegrationService/IntegrationService.asmx?wsdl"

body1="""<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <OpenSession xmlns="http://parsec.ru/Parsec3IntergationService">
      <domain>SYSTEM</domain>
      <userName>user</userName>
      <password>pass</password>
    </OpenSession>
  </soap:Body>
</soap:Envelope>"""
body1 = body1.encode('utf-8')
session = requests.session()
session.headers = {"Content-Type": "text/xml; charset=utf-8"}
session.headers.update({"Content-Length": str(len(body1))})
response = session.post(url=endpoint, data=body1, verify=False)

print(response.content)

SESID = re.search(pattern, SessionID)
print (SESID)

输出

b'<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><OpenSessionResponse xmlns="http://parsec.ru/Parsec3IntergationService"><OpenSessionResult><Result>0</Result><Value><SessionID>d623e923-1aac-4d59-9754-ab279c191860</SessionID><RootOrgUnitID>f7c724d2-7e24-4257-8271-87caca6909f9</RootOrgUnitID><RootTerritoryID>88ef0e32-3b6f-467c-a0ec-0733317f6757</RootTerritoryID></Value></OpenSessionResult></OpenSessionResponse></soap:Body></soap:Envelope>'

如何获取<SessionID>d623e923-1aac-4d59-9754-ab279c191860</SessionID>并将其添加到变量SESID中


Tags: orghttpsessionwwwbodyxmlsoaputf
1条回答
网友
1楼 · 发布于 2024-10-08 19:22:39

一旦将输出存储在变量中,就需要使用UTF-8编码格式将其从字节转换为字符串

然后,您可以按照自己的意愿分割字符串以获得SessionID

Here's how

x=b'<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><OpenSessionResponse xmlns="http://parsec.ru/Parsec3IntergationService"><OpenSessionResult><Result>0</Result><Value><SessionID>d623e923-1aac-4d59-9754-ab279c191860</SessionID><RootOrgUnitID>f7c724d2-7e24-4257-8271-87caca6909f9</RootOrgUnitID><RootTerritoryID>88ef0e32-3b6f-467c-a0ec-0733317f6757</RootTerritoryID></Value></OpenSessionResult></OpenSessionResponse></soap:Body></soap:Envelope>'

x=str(x,"UTF-8")

# 12 here is equivalent to len("</SessionID>") which I prefer you'd use
# because you would be able to extract anything else by just replacing the keyword

sid=x[ x.index("<SessionID>") : x.index("</SessionID>")+12 ]

print(sid)

这将为您提供以下输出

'<SessionID>d623e923-1aac-4d59-9754-ab279c191860</SessionID>'

相关问题 更多 >

    热门问题