第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

python 3.x 中的站點地圖 xml 解析

python 3.x 中的站點地圖 xml 解析

動漫人物 2022-12-06 15:16:37
我的 xml 結(jié)構(gòu)如下<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">    <url>        <loc>hello world 1</loc>        <image:image>            <image:loc>this is image loc 1</image:loc>            <image:title>this is image title 1</image:title>        </image:image>        <lastmod>2019-06-19</lastmod>        <changefreq>daily</changefreq>        <priority>0.25</priority>    </url>    <url>        <loc>hello world 2</loc>        <image:image>            <image:loc>this is image loc 2</image:loc>            <image:title>this is image title 2</image:title>        </image:image>        <lastmod>2020-03-19</lastmod>        <changefreq>daily</changefreq>        <priority>0.25</priority>    </url></urlset>我只想得到hello world 1hello world 2我的 python 代碼如下:import xml.etree.ElementTree as ETtree = ET.parse('test.xml')root = tree.getroot()for url in root.findall('url'):    loc = url.find('loc').text    print(loc)不幸的是,它什么也沒給我。但是當我將 xml 更改為<urlset>    <url>        <loc>hello world 1</loc>        <lastmod>2019-06-19</lastmod>        <changefreq>daily</changefreq>        <priority>0.25</priority>    </url>    <url>        <loc>hello world 2</loc>        <lastmod>2020-03-19</lastmod>        <changefreq>daily</changefreq>        <priority>0.25</priority>    </url></urlset>它給了我正確的結(jié)果。hello world 1hello world 2我該怎么做才能在不更改 xml 的情況下獲得正確的結(jié)果?因為修改 10000 多行文件沒有任何意義。愛
查看完整描述

2 回答

?
牛魔王的故事

TA貢獻1830條經(jīng)驗 獲得超3個贊

對您的代碼的(不雅)修復(fù)是:


import xml.etree.ElementTree as ET

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

root = tree.getroot()


# In find/findall, prefix namespaced tags with the full namespace in braces

for url in root.findall('{http://www.sitemaps.org/schemas/sitemap/0.9}url'):

    loc = url.find('{http://www.sitemaps.org/schemas/sitemap/0.9}loc').text

    print(loc)

這是因為您必須使用定義 XML 的命名空間來限定標記名稱。有關(guān)如何使用名稱空間find和findall方法的詳細信息來自Parse XML namespace with Element Tree findall


查看完整回答
反對 回復(fù) 2022-12-06
?
繁星點點滴滴

TA貢獻1803條經(jīng)驗 獲得超3個贊

如果你不想弄亂命名空間,這是比公認的答案更簡單的解決方案,而且更優(yōu)雅,使用通用的 xpath 查詢:


import lxml.etree



tree = lxml.etree.parse('test.xml')


for url in tree.xpath("//*[local-name()='loc']/text()"):

    print(url)

如果你更喜歡使用 xml 命名空間,你應(yīng)該這樣做:


import lxml.etree



tree = lxml.etree.parse('test.xml')


namespaces = {

    'sitemapindex': 'http://www.sitemaps.org/schemas/sitemap/0.9',

}


for url in tree.xpath("//sitemapindex:loc/text()", namespaces=namespaces):

    print(url)

如果你更喜歡直接從內(nèi)存而不是文件加載 xml 數(shù)據(jù),你可以使用 lxml.etree.fromstring 而不是 lxml.etree.parse。


查看完整回答
反對 回復(fù) 2022-12-06
  • 2 回答
  • 0 關(guān)注
  • 111 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號