python-3.x 我想每次都遍历文本文件以读取xml请求并向url发送POST请求

xhv8bpkk  于 2022-11-19  发布在  Python
关注(0)|答案(1)|浏览(132)

我有一个包含如下数据的示例文本文件。如何编写代码来获取第一个tc标记和匹配的ServiceRQ标记,它是tc标记旁边。文本文件包含一行的一致间隙后,每个tc标记和ServiceRQ标记在整个文本文件中,并作出后请求URL我的代码如下所示:sample.txt

**Sample.txt**
<tc>Hello</tc>
<ServiceRQ>Some Data</ServiceRQ>

<tc>Hello</tc>
<ServiceRQ>Some Date</ServiceRQ>

 <tc>World</tc>
<ServiceRQ>Some Date</ServiceRQ>

import requests
url = "url to place"
payload = """soapenv:Header>                                                            
                    I want to put tc here every time reading from text file 
             </soapenv:Header>
             <soapenv:Body>
                    And ServiceRQ here for that tc
             </soapenv:Body>"""

headers = {
      'Content-Type': 'application/xml'
 }

response = request.request("POST", url, headers=headers, data=-payload)

有没有办法每次都遍历文本文件,首先获取tc标记,然后获取ServiceRQ标记,并发出POST请求,然后再次转到文本文件,获取第二个tc和第二个ServiceRQ,并发出POST请求,然后继续。另外,请您帮助我使用正则表达式获取ServiceRQ标记沿着它们之间的数据。我还需要开始和结束标记。

5vf7fwbs

5vf7fwbs1#

您需要regular expressions来捕获这些标记。
我给予在xml_text中,每个<tc></tc>后面都跟着一个<ServiceRQ></ServiceRQ>,并且如果<tc><ServiceRQ>的标签数量不同,send_requests()就会抛出一个错误(也就是说,我检查了它们的长度,但没有检查它们的交替):

import re
import requests
from typing import List, Tuple

xml_text = open("file.xml", 'r').read()

def get_matches(input_text: str) -> Tuple[List, List]:
    matched_tc = re.findall(r"<tc>.*?</tc>", input_text)
    matched_servicerq = re.findall(r"<ServiceRQ>.*?</ServiceRQ>", input_text)
    return matched_tc, matched_servicerq

def send_requests(input_text: str) -> None:
    matched_tc, matched_servicerq = get_matches(input_text)
    if len(matched_tc) != len(matched_servicerq):
        raise Exception("Number of <tc> tags different from number of <ServiceRQ> tags")
    for i in range(len(matched_tc)):
        try:
            url = "url to place"
            payload = f"""<soapenv:Header>
                                {matched_tc[i]}
                         </soapenv:Header>
                         <soapenv:Body>
                                {matched_servicerq[i]}
                         </soapenv:Body>"""
            headers = {
                'Content-Type': 'application/xml'
            }
            response = requests.request("POST", url, headers=headers, data=payload)
        except Exception as ex:
            print(ex)
        else:
            print(response)  # Do something with the response.

send_requests(xml_text)

相关问题