正在解析 Python 中 XML 节点的文本

Parsing text from XML node in Python

我正在尝试从这样的站点地图中提取网址:https://www.bestbuy.com/sitemap_c_0.xml.gz

我解压缩了 .xml.gz 文件并将其保存为 .xml 文件。结构如下所示:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xhtml="http://www.w3.org/1999/xhtml" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
<url>
    <loc>https://www.bestbuy.com/</loc>
    <priority>0.0</priority>
</url>
<url>
    <loc>https://www.bestbuy.com/site/3d-printers/3d-printer-filament/pcmcat335400050008.c?id=pcmcat335400050008</loc>
    <priority>0.0</priority>
</url>
<url>
    <loc>https://www.bestbuy.com/site/3d-printers/3d-printing-accessories/pcmcat748300527647.c?id=pcmcat748300527647</loc>
    <priority>0.0</priority>
</url>

我正在尝试使用 ElementTree 提取整个文件中 loc 节点内的所有 URL,但很难让它正常工作。

根据文档,我正在尝试这样的操作:

import xml.etree.ElementTree as ET
tree = ET.parse('my_local_filepath')
root = tree.getroot()

value = root.findall(".//loc")

然而,没有任何东西被加载到值中。我的目标是提取 loc 节点之间的所有 URL,并将其打印到一个新的平面文件中。我哪里错了?

我们可以遍历 URL,将它们放入列表中,然后将它们写入文件:

from xml.etree import ElementTree as ET

tree = ET.parse('test.xml')
root = tree.getroot()

name_space = '{http://www.sitemaps.org/schemas/sitemap/0.9}'

urls = []
for child in root.iter():
    for block in child.findall('{}url'.format(name_space)):
        for url in block.findall('{}loc'.format(name_space)):
            urls.append('{}\n'.format(url.text))

with open('sample_urls.txt', 'w+') as f:
    f.writelines(urls)
  • 请注意,我们需要从开放的 urlset 定义中附加名称 space 以正确解析 xml

您的尝试很接近,但正如 mzjn 在评论中所说,您没有考虑默认命名空间 (xmlns="http://www.sitemaps.org/schemas/sitemap/0.9")。

这是一个如何考虑命名空间的示例:

import xml.etree.ElementTree as ET
tree = ET.parse('my_local_filepath')

ns = {"sm": "http://www.sitemaps.org/schemas/sitemap/0.9"}

for elem in tree.findall(".//sm:loc", ns):
    print(elem.text)

输出:

https://www.bestbuy.com/
https://www.bestbuy.com/site/3d-printers/3d-printer-filament/pcmcat335400050008.c?id=pcmcat335400050008
https://www.bestbuy.com/site/3d-printers/3d-printing-accessories/pcmcat748300527647.c?id=pcmcat748300527647

请注意,我使用了命名空间前缀 sm,但您可以使用任何 NCName.

See here 了解有关使用 ElementTree 中的命名空间解析 XML 的更多信息。

我知道这有点像僵尸回复,但实际上我只是在 github 上发布了一个工具,它可以满足您的需求。在 Python!因此,请随意从源代码中获取您需要的内容(或按原样使用)。我想我会对此发表评论,以便遇到此主题的其他人会看到它。

这里是:https://github.com/tcaldron/xmlscrape