首先解析XML站点地图获取URL列表,需用requests获取内容并用ElementTree解析;由于存在命名空间,必须指定前缀如{"ns": "http://www.sitemaps.org/schemas/sitemap/0.9"}才能正确提取loc、lastmod等信息;若根节点为<sitemapindex>,则为索引文件,需递归解析每个子链接;注意事项包括检查响应状态、添加User-Agent、遵守robots.txt及控制请求频率。

解析网页中的XML站点地图(sitemap)是Python爬虫中常见的任务,尤其在需要批量抓取网站页面时。通过读取sitemap,可以快速获取网站公开的所有重要URL列表,提高爬取效率和准确性。
大多数网站会在根目录下提供 sitemap.xml 文件,例如 https://www.php.cn/link/5211bda24f5c44114c473a74b8bdf361。你可以使用 requests 库发起HTTP请求获取内容,再用 xml.etree.ElementTree 解析XML结构。
示例代码:
import requests import xml.etree.ElementTree as ET <p>url = "<a href="https://www.php.cn/link/5211bda24f5c44114c473a74b8bdf361">https://www.php.cn/link/5211bda24f5c44114c473a74b8bdf361</a>" response = requests.get(url) response.raise_for_status() # 检查请求是否成功</p><h1>解析XML内容</h1><p>root = ET.fromstring(response.content)</p><p><span>立即学习</span>“<a href="https://pan.quark.cn/s/00968c3c2c15" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">Python免费学习笔记(深入)</a>”;</p>
标准的sitemap遵循特定的XML命名空间格式。常见结构包含 <urlset> 根节点,其下每个 <url> 子节点代表一个页面,通常包括以下字段:
由于XML中使用了命名空间(namespace),直接查找标签会失败。必须在解析时指定命名空间前缀。
正确处理命名空间的方法:
namespace = {"ns": "http://www.sitemaps.org/schemas/sitemap/0.9"}
<p>for url_elem in root.findall("ns:url", namespace):
loc = url_elem.find("ns:loc", namespace).text
lastmod = url_elem.find("ns:lastmod", namespace)
print("URL:", loc)
if lastmod is not None:
print("Last Modified:", lastmod.text)</p>大型网站常使用站点地图索引(sitemap index),即主文件列出多个子sitemap链接。这种情况下,需先解析主文件中的 <sitemap> 节点,再逐个抓取子文件。
判断当前XML是索引还是普通站点地图:
示例:递归解析所有子站点地图
def parse_sitemap_index(content):
    root = ET.fromstring(content)
    namespace = {"ns": "http://www.sitemaps.org/schemas/sitemap/0.9"}
    sitemaps = []
<pre class='brush:php;toolbar:false;'>for sitemap in root.findall("ns:sitemap", namespace):
    loc = sitemap.find("ns:loc", namespace).text
    sitemaps.append(loc)
return sitemaps之后对每个返回的子链接再次调用解析函数提取实际URL。
使用Python解析XML站点地图时应注意以下几点:
基本上就这些。掌握这些方法后,你就能高效地从各类XML站点地图中提取所需链接,为后续的网页抓取打下基础。
以上就是Python爬虫如何解析网页中的XML站点地图(sitemap)_Python爬虫解析XML站点地图指南的详细内容,更多请关注php中文网其它相关文章!
                        
                        每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
                
                                
                                
                                
                                
                                
                                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号