Python代码重复打印问题排查:如何实现仅打印一次?
Hey there! I see the issue right away—your code is printing the same Version and Source data multiple times because you've placed the print statement inside a loop that iterates over all child nodes of air:EDS_AirCheckInRQ. Let me break this down and fix it for you.
Why You're Getting Duplicate Output
Looking at your code:
- You first fetch all child nodes of
air:EDS_AirCheckInRQinto thenodesvariable - Then you loop through each child node with
for x in nodes - Inside the loop, you repeatedly query and print the same
Versionattribute andcom:Sourcenode
Since air:EDS_AirCheckInRQ has 6 child nodes, the loop runs 6 times—hence 6 identical lines of output.
Fixed Code
Move the print statement outside the loop, because Version and com:Source are properties of the parent air:EDS_AirCheckInRQ node (not its children). If you still need to process the child nodes, keep the loop but use it for child-specific data:
from simplified_scrapy import SimplifiedDoc, utils #simplified_scrapy is framework for extracting data xml = utils.getFileContent('check_in.xml') doc = SimplifiedDoc(xml) #SimplifiedDoc is a library for parsing data such as HTML and XML # Grab the main parent node once main_checkin_node = doc.select('air:EDS_AirCheckInRQ') # Print the static data ONCE, outside the loop print(main_checkin_node['Version'], main_checkin_node.select('com:Source')) # If you need to process child nodes, do that here (optional) child_nodes = main_checkin_node.children for node in child_nodes: # Example: Print each child node's tag for debugging print(f"Child node tag: {node.tag}")
What This Does
- The
Versionandcom:Sourcevalues are fetched once from the parent node and printed a single time - The loop (if kept) now handles only child node-specific logic, without repeating the static parent data
This will give you the single output line you want, while still letting you work with the child nodes if needed.
内容的提问来源于stack exchange,提问作者Minhaj Khan

