карта сайта xml разбор в python 3.x - PullRequest
0 голосов
/ 25 мая 2020

Моя xml структура ниже

<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 1
hello world 2

Мой python код ниже:

import xml.etree.ElementTree as ET
tree = 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>

, это дает мне правильный результат.

hello world 1
hello world 2

Что я могу сделать с получить правильный результат без изменения моего xml? Потому что нет смысла изменять более 10000 строк файла.

TIA

1 Ответ

0 голосов
/ 25 мая 2020

(неизящное) исправление для вашего кода:

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. Подробная информация о том, как использовать методы find и findall с пространствами имен, взята из пространства имен Parse XML с помощью Element Tree findall

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...