Reputation: 133
I am using Python3 Beautiful Soup to scrap a website. This is the XML data I am getting.
<?xml version="1.0" encoding="utf-8"?>
<title type="text">MATERIALSET('R100100100')</title>
<updated>2018-05-11T04:28:47Z</updated>
<category term="ZPOC_BOT_PUR_GRP_SRV.MATERIAL" scheme="http://schemas.microsoft.com/ado/2007/08/dataservices/scheme"/>
<link href="MATERIALSET('R100100100')" rel="self" title="MATERIAL"/>
<content type="application/xml">
<m:properties>
<d:MATNR>R100100100</d:MATNR>
<d:WERKS>Z100</d:WERKS>
<d:MENGE> 1.000</d:MENGE>
<d:EEIND>29.06.2018</d:EEIND>
<d:BANFN>5000000041</d:BANFN>
</m:properties>
</content>
</entry>
I just want to extract the data in d:BANFN. If I directly write soup.select('d:BANFN") it shows an error of 'nth_child_of_type'. I did go through some of the questions in Stackoverflow here are the links - Getting the nth element using BeautifulSoup and selecting second child in beautiful soup with soup.select? But nothing helps. Please help.
Upvotes: 1
Views: 278
Reputation: 701
In xml file there should be the starting tag for entry
attribute then only you will be able to parse xml file:
<!-- Sample.xml contains following data: -->
<?xml version="1.0" encoding="utf-8"?>
<entry>
<title type="text">MATERIALSET('R100100100')</title>
<updated>2018-05-11T04:28:47Z</updated>
<category term="ZPOC_BOT_PUR_GRP_SRV.MATERIAL" scheme="http://schemas.microsoft.com/ado/2007/08/dataservices/scheme"/>
<link href="MATERIALSET('R100100100')" rel="self" title="MATERIAL"/>
<content type="application/xml">
<m:properties>
<d:MATNR>R100100100</d:MATNR>
<d:WERKS>Z100</d:WERKS>
<d:MENGE> 1.000</d:MENGE>
<d:EEIND>29.06.2018</d:EEIND>
<d:BANFN>5000000041</d:BANFN>
</m:properties>
</content>
</entry>
from bs4 import BeautifulSoup
with open("sample.xml", "r") as f: # opening xml file
content = f.read() # xml content stored in this variable and decode to utf-8
soup = BeautifulSoup(content, 'lxml') #parse content to BeautifulSoup Module
print("BANFN value : {}".format([ item.text for item in soup.find_all("d:banfn")][0])) #required result
#output:
BANFN value : 5000000041
Upvotes: 1