【问题标题】:Parsing xml file using beautifulsoup4使用beautifulsoup4解析xml文件
【发布时间】:2018-10-12 14:40:58
【问题描述】:

我只想从 profile name="4" 中提取 stuff 标签。我在下面编写了一个代码,它提取了 profile name = "4" 下的所有内容,但是有没有办法从那里收集所有的东西标签,或者我必须使用 split 来获取东西标签内的文本。我拥有的 xml 文件要长得多,因此使用 split 是可行的,但解析数据需要更长的时间。

这是python代码

import bs4 as bs

# opens xml file and allows bs4 to parse xml file
xml_file = open('file.xml')
soup = bs.BeautifulSoup(xml_file, 'html.parser')

#extracts and prints all tags under profile name = "4"
stuff = soup.find_all('profile', {'name':"4"})
print stuff

这是 xml 文件,其名称为 file.xml。我想从个人资料名称中提取东西标签=“4”

<profiles>
    <profile name="1">
        <content>apple</content>
    </profile>
    <profile name="2">
        <content>peas</content>
    </profile>
    <profile name="3">
        <stuff>bear</stuff>
    </profile>
    <profile name="4">
        <content>cat</content>
        <data>
            <stuff>fish</stuff>
        </data>
        <stuff>hat</stuff>
    </profile>
</profiles>

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    对内部标签做同样的事情

    print([i.find_all('stuff') for i in stuff])
    

    如果您只需要标签内的数据

    for i in stuff:
        for x in i.find_all('stuff'):
            print(x.next) 
    

    输出:

    fish
    hat
    

    【讨论】:

      猜你喜欢
      • 2021-12-07
      • 2014-09-16
      • 1970-01-01
      • 2021-03-27
      • 2012-07-15
      • 2013-05-29
      • 2012-12-16
      • 2011-09-01
      • 2021-01-02
      相关资源
      最近更新 更多