首先解析XML站点地图获取URL列表,需用requests获取内容并用ElementTree解析;由于存在命名空间,必须指定前缀如{"ns": "http://www.sitemaps.org/schemas/sitemap/0.9"}才能正确提取loc、lastmod等信息;若根节点为,则为索引文件,需递归解析每个子链接;注意事项包括检查响应状态、添加User-Agent、遵守robots.txt及控制请求频率。
解析网页中的XML站点地图(sitemap)是Python爬虫中常见的任务,尤其在需要批量抓取网站页面时。通过读取sitemap,可以快速获取网站公开的所有重要URL列表,提高爬取效率和准确性。
大多数网站会在根目录下提供 sitemap.xml 文件,例如 https://www./link/5211bda24f5c44114c473a74b8bdf361。你可以使用 requests 库发起HTTP请求获取内容,再用 xml.etree.ElementTree 解析XML结构。
示例代码:
import requests import xml.etree.ElementTree as ETurl = "https://www./link/5211bda24f5c44114c473a74b8bdf361" response = requests.get(url) response.raise_for_status() # 检查请求是否成功
解析XML内容
root = ET.fromstring(response.content)
标准的sitemap遵循特定的XML命名空间格式。常见结构包含
由于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)
Index)大型网站常使用站点地图索引(sitemap index),即主文件列出多个子sitemap链接。这种情况下,需先解析主文件中的
判断当前XML是索引还是普通站点地图:
示例:递归解析所有子站点地图
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站点地图时应注意以下几点:
基本上就这些。掌握这些方法后,你就能高效地从各类XML站点地图中提取所需链接,为后续的网页抓取打下基础。