[英]Parsing text from XML node in Python
我正在嘗試從這樣的站點地圖中提取 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 並將其打印到一個新的平面文件中。 我哪里錯了?
您的嘗試很接近,但就像 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 。
我們可以遍歷 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)
我知道這有點像僵屍回復,但實際上我只是在 github 上發布了一個工具,它可以完全滿足您的需求。 在 Python 中! 因此,請隨意從源代碼中獲取您需要的內容(或按原樣使用)。 我想我會對此發表評論,以便遇到此線程的其他人會擁有它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.