Issue
From my previous question, I asked how to parse multiple siblings from the same child, now I am curious how you take each output and have it equal to a unique variable. For example, I want Unkown out equal to Occupation and 656 equal to CarrierCode, and so on.
from bs4 import BeautifulSoup
xml='''
from bs4 import BeautifulSoup
xml='''
<AdditonalAttributes>
<Attribute>
<Name> Occupation </Name>
<Value> Unknown </Value>
</Attribute>
<Attribute>
<Name> CarrierCode </Name>
<Value> 656 </Value>
</Attribute>
<AdditonalAttributes>
'''
soup = BeautifulSoup(xml, 'xml')
for a in soup.select('Attribute'):
if a.Name.get_text(strip=True) in ['Occupation','CarrierCode']:
print(a.Value.get_text(strip=True))
Output:
Unknown
656
Solution
Assignment to variables is not clear but if you like to go the way along with BeautifulSoup
to get a dict of your attributes:
dict(a.stripped_strings for a in soup.select('Attribute'))
Example
from bs4 import BeautifulSoup
xml='''
<AdditonalAttributes>
<Attribute>
<Name> Occupation </Name>
<Value> Unknown </Value>
</Attribute>
<Attribute>
<Name> CarrierCode </Name>
<Value> 656 </Value>
</Attribute>
<AdditonalAttributes>
'''
soup = BeautifulSoup(xml, 'xml')
dict(a.stripped_strings for a in soup.select('Attribute'))
Output
{'Occupation': 'Unknown', 'CarrierCode': '656'}
Answered By - HedgeHog
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.