如何用Python requests模块提取XML及SOAP响应的单个标签内容?
Extracting Single Tag Content from SOAP XML Response in Python
Got it, let's break this down. You’ve already used requests.get() to call your SOAP service and have an XML response in hand—now you need to pull out the value from a specific tag like <aa:TestMode>. Here are two reliable approaches to do this, depending on your needs:
Method 1: Use Python’s Built-in xml.etree.ElementTree
No extra packages needed here—great if you want to stick to the standard library. The key thing to remember is handling XML namespaces (those xmlns: prefixes like aa), since SOAP responses almost always use them.
import requests import xml.etree.ElementTree as ET # Your existing request code response = requests.get(url, data=body, headers=headers) xml_content = response.text # Parse the XML root = ET.fromstring(xml_content) # Define the namespaces from your response (match the xmlns values exactly) namespaces = { 'aa': 'example.com/api', 'soap': 'http://schemas.xmlsoap.org/soap/envelope/' } # Find the specific tag (use .// to search recursively through all levels) test_mode_tag = root.find('.//aa:TestMode', namespaces=namespaces) # Extract and clean the text content if test_mode_tag is not None: test_mode_value = test_mode_tag.text.strip() print(f"TestMode value: {test_mode_value}") else: print("TestMode tag not found in response")
Method 2: Use lxml for More Powerful XML Handling
If you’re dealing with complex XML or need advanced XPath support, lxml is a great choice. You’ll need to install it first:
pip install lxml
Then use this code:
import requests from lxml import etree # Your existing request code response = requests.get(url, data=body, headers=headers) # Parse the XML root = etree.fromstring(response.text) # Define namespaces namespaces = {'aa': 'example.com/api'} # Use XPath to directly get the tag's text content test_mode_values = root.xpath('//aa:TestMode/text()', namespaces=namespaces) # Handle the result (XPath returns a list of matches) if test_mode_values: # Grab the first match (since you want a single tag) test_mode_value = test_mode_values[0].strip() print(f"TestMode value: {test_mode_value}") else: print("TestMode tag not found in response")
Key Notes:
- Namespaces are critical: If you skip defining the
namespacesdictionary and try to search forTestModewithout theaa:prefix, the parser won’t find the tag. Always match thexmlnsvalues exactly from your SOAP response. - Recursive search: Using
.//(in ElementTree) or//(in XPath) lets you search for the tag anywhere in the XML structure, so you don’t have to write out the full nested path from the root. - Handle missing tags: Always check if the tag exists before accessing
.textto avoidAttributeErrorcrashes.
内容的提问来源于stack exchange,提问作者twindad
相关产品推荐
相关产品推荐

