[使用BeautifulSoup显示XML树结构

问题描述 投票:1回答:3

[使用新的XML结构时,先查看全局图片总是有帮助的。

BeautifulSoup加载时:

import requests, bs4
s = requests.get('https://www.w3schools.com/xml/cd_catalog.xml').text
x = bs4.BeautifulSoup(s, 'xml')
print(x)

有内置的方法来显示其深度不同的树结构吗?


https://www.w3schools.com/xml/cd_catalog.xml的示例,带有maxdepth=0,它将是:

CATALOG

使用maxdepth=1,它将是:

CATALOG
  CD 
  CD
  CD
  ...

并且使用maxdepth=2,它将是:

CATALOG
  CD 
    TITLE
    ARTIST
    COUNTRY
    COMPANY
    PRICE
    YEAR
  CD 
    TITLE
    ARTIST
    COUNTRY
    COMPANY
    PRICE
    YEAR
  ...
python xml beautifulsoup tree
3个回答
1
投票

我使用了xmltodict 0.12.0(通过anaconda安装),该文件可用于xml解析,但不能用于深度查看。就像其他字典一样工作。从这里开始,进行深度计数递归应该是一种方法。

import requests, xmltodict

s = requests.get('https://www.w3schools.com/xml/cd_catalog.xml').text
x = xmltodict.parse(s, process_namespaces=True)

for key in x:
    print(x[key])

1
投票

这是一种快速的方法:使用prettify()函数对其进行结构化,然后通过正则表达式获取缩进和打开标记的名称(在这种情况下,在打开标记内捕获大写单词)。如果pretify()的压痕符合深度规格,则以指定的压痕尺寸进行打印。

import requests, bs4
import re

maxdepth = 1
indent_size = 2
s = requests.get('https://www.w3schools.com/xml/cd_catalog.xml').text
x = bs4.BeautifulSoup(s, 'xml').prettify()

for line in x.split("\n"):
    match = re.match("(\s*)<([A-Z]+)>", line)
    if match and len(match.group(1)) <= maxdepth:
        print(indent_size*match.group(1) + match.group(2))

0
投票

这里是一个没有BeautifulSoup的解决方案。

import requests
s = requests.get('https://www.w3schools.com/xml/cd_catalog.xml').text
array = []

tab_size = 2
target_depth = 2

for element in s.split('\n'):
    depth = (len(element) - len(element.lstrip())) / tab_size
    if depth <= target_depth:
        print(' ' * int(depth) + element)
© www.soinside.com 2019 - 2024. All rights reserved.