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

解析网页中的XML站点地图(sitemap)是Python爬虫中常见的任务,尤其在需要批量抓取网站页面时。通过读取sitemap,可以快速获取网站公开的所有重要URL列表,提高爬取效率和准确性。
获取并读取XML站点地图
大多数网站会在根目录下提供 sitemap.xml 文件,例如 https://www.php.cn/link/5211bda24f5c44114c473a74b8bdf361。你可以使用 requests 库发起HTTP请求获取内容,再用 xml.etree.ElementTree 解析XML结构。
示例代码:
import requests import xml.etree.ElementTree as ETurl = "https://www.php.cn/link/5211bda24f5c44114c473a74b8bdf361" response = requests.get(url) response.raise_for_status() # 检查请求是否成功
解析XML内容
root = ET.fromstring(response.content)
立即学习“Python免费学习笔记(深入)”;
理解Sitemap的XML结构
标准的sitemap遵循特定的XML命名空间格式。常见结构包含
- loc:页面的URL地址
- lastmod:最后修改时间(可选)
- changefreq:更新频率(如daily、weekly)
- priority:优先级(0.0 到 1.0)
由于XML中使用了命名空间(namespace),直接查找标签会失败。必须在解析时指定命名空间前缀。
正确处理命名空间的方法:
namespace = {"ns": "http://www.sitemaps.org/schemas/sitemap/0.9"}
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)
处理分层站点地图(Sitemap Index)
大型网站常使用站点地图索引(sitemap index),即主文件列出多个子sitemap链接。这种情况下,需先解析主文件中的
判断当前XML是索引还是普通站点地图:
- 若根节点为
,则是索引文件 - 若根节点为
,则是URL列表文件
示例:递归解析所有子站点地图
def parse_sitemap_index(content):
root = ET.fromstring(content)
namespace = {"ns": "http://www.sitemaps.org/schemas/sitemap/0.9"}
sitemaps = []
for sitemap in root.findall("ns:sitemap", namespace):
loc = sitemap.find("ns:loc", namespace).text
sitemaps.append(loc)
return sitemaps之后对每个返回的子链接再次调用解析函数提取实际URL。
注意事项与最佳实践
使用Python解析XML站点地图时应注意以下几点:
- 始终检查HTTP响应状态,避免因404或403导致程序中断
- 添加User-Agent头模拟浏览器请求,防止被反爬机制拦截
- 遵守robots.txt规则,尊重网站的爬取策略
- 控制请求频率,避免对目标服务器造成压力
- 考虑使用 lxml 库替代内置ET,支持更复杂的XPath查询和更好的性能
基本上就这些。掌握这些方法后,你就能高效地从各类XML站点地图中提取所需链接,为后续的网页抓取打下基础。










