【问题标题】:Fetching nth child using BeautifulSoup Python3使用 BeautifulSoup Python3 获取第 n 个孩子
【发布时间】:2018-10-21 12:02:30
【问题描述】:

我正在使用 Python3 Beautiful Soup 来废弃一个网站。这是我得到的 XML 数据。

<?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>

我只想提取 d:BANFN 中的数据。如果我直接写soup.select('d:BANFN") 它会显示'nth_child_of_type'的错误。我确实在Stackoverflow中解决了一些问题,这里是链接 - Getting the nth element using BeautifulSoupselecting second child in beautiful soup with soup.select? 但没有任何帮助。 请帮忙。

【问题讨论】:

  • 入口标签从哪里开始?
  • 出于隐私和安全目的,我不得不删除一些标签。很抱歉。

标签: python-3.x web-scraping


【解决方案1】:

在 xml 文件中应该有 entry 属性的起始标签,然后只有你才能解析 xml 文件:

<!-- 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

【讨论】:

  • 工作。谢谢
  • @SarthakMahapatra 随时:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-02
  • 1970-01-01
  • 1970-01-01
  • 2017-03-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多