首页 > 解决方案 > 用 Python 解析这个 XML 站点地图的最有效方法是什么?

问题描述

我有以下要解析的站点地图:

<?xml version="1.0" encoding="UTF-8"?> 
  <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <url> 
      <loc>https://www.example.com/examplea</loc> 
      <priority>0.5</priority> 
      <lastmod>2019-03-14</lastmod> 
      <changefreq>daily</changefreq> 
   </url> 
   <url> 
     <loc>https://www.example.com/exampleb</loc> 
     <priority>0.5</priority> 
     <lastmod>2019-03-14</lastmod> 
     <changefreq>daily</changefreq> 
   </url> 
</urlset>

使用 Python 获取 loc 标记中的 url 链接的最快方法是什么?

我尝试使用 ElementTree,但我认为它因为命名空间而不起作用。

我需要得到“ https://www.example.com/examplea ”和“ https://www.example.com/exampleab

标签: pythonxmlsitemap

解决方案


import re

str = """
<?xml version="1.0" encoding="UTF-8"?> 
  <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <url> 
      <loc>https://www.example.com/examplea</loc> 
      <priority>0.5</priority> 
      <lastmod>2019-03-14</lastmod> 
      <changefreq>daily</changefreq> 
   </url> 
   <url> 
     <loc>https://www.example.com/exampleb</loc> 
     <priority>0.5</priority> 
     <lastmod>2019-03-14</lastmod> 
     <changefreq>daily</changefreq> 
   </url> 
</urlset>
"""  
url = re.findall("<loc>(.*?)</loc>", str)

推荐阅读