Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
1.5 kB
0
Indexable
Never
import requests
from bs4 import BeautifulSoup
import csv

# Define the XML request body
xml_request = """
<Request>
    <Parameter1>Value1</Parameter1>
    <Parameter2>Value2</Parameter2>
</Request>
"""

# Define the URL for the POST request
url = 'https://example.com/api/endpoint'

# Set the headers for the request
headers = {'Content-Type': 'application/xml'}

# Make the HTTP POST request
response = requests.post(url, headers=headers, data=xml_request)

# Check if the request was successful (status code 200)
if response.status_code == 200:
    # Parse the XML response using BeautifulSoup
    soup = BeautifulSoup(response.text, 'xml')
    
    # Define a CSV file to write the parsed data
    csv_filename = 'response_data.csv'

    # Extract data from the XML response and write it to a CSV file
    with open(csv_filename, mode='w', newline='') as csv_file:
        csv_writer = csv.writer(csv_file)
        
        # Write CSV headers (modify these based on your XML structure)
        csv_writer.writerow(['Field1', 'Field2'])
        
        # Extract data from the XML response and write it to the CSV file
        for item in soup.find_all('Item'):
            field1 = item.find('Field1').text
            field2 = item.find('Field2').text
            csv_writer.writerow([field1, field2])
    
    print(f'Response data has been written to {csv_filename}')
else:
    print(f'HTTP request failed with status code {response.status_code}')