【发布时间】:2018-10-17 04:34:03
【问题描述】:
我正在尝试从这样的站点地图中提取 URL: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 并将其打印到一个新的平面文件中。我哪里错了?
【问题讨论】:
-
您没有考虑命名空间。见docs.python.org/3/library/…
标签: python xml python-3.x elementtree