首先确认目标URL是否返回XML内容,如sitemap.xml或RSS源;接着用requests库获取数据并检查状态码;然后使用xml.etree.ElementTree解析,注意处理命名空间,可用命名空间字典或通配符{*};最后将提取的数据保存为CSV或JSON文件。全过程需遵守robots.txt并控制请求频率。

从网页上抓取 XML 数据是网络爬虫中常见的任务,尤其在处理 API 接口、站点地图(sitemap.xml)或结构化数据时非常实用。下面介绍如何使用 Python 实现 XML 数据的抓取与解析,适合初学者快速上手。
不是所有网页都提供 XML 数据。你需要先确认目标 URL 是否返回的是 XML 内容。常见 XML 资源包括:
打开浏览器访问该链接,如果能看到结构化的标签内容(如 <urlset>、<item>、<title> 等),说明是有效的 XML 资源。
Python 中推荐使用 requests 库发送 HTTP 请求获取 XML 原文。
示例代码:
import requests
<p>url = "<a href="https://www.php.cn/link/5211bda24f5c44114c473a74b8bdf361">https://www.php.cn/link/5211bda24f5c44114c473a74b8bdf361</a>"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
}</p><p>response = requests.get(url, headers=headers)</p><p>if response.status_code == 200:
xml_data = response.text
print(xml_data)
else:
print("请求失败,状态码:", response.status_code)</p>注意添加 User-Agent 防止被服务器拒绝。确保网络可达且目标支持直接访问。
Python 标准库中的 xml.etree.ElementTree 可以高效解析 XML 结构。
解析 sitemap.xml 示例:
import xml.etree.ElementTree as ET
<p>root = ET.fromstring(xml_data)</p><h1>常见命名空间处理(如 sitemap)</h1><p>namespaces = {
'ns': '<a href="https://www.php.cn/link/654f3a10edb3bb1755a43cc4f9be9dc6">https://www.php.cn/link/654f3a10edb3bb1755a43cc4f9be9dc6</a>'
}</p><p>for url in root.findall('ns:url', namespaces):
loc = url.find('ns:loc', namespaces).text
lastmod = url.find('ns:lastmod', namespaces).text
print(f"页面地址: {loc}, 最后更新: {lastmod}")</p>如果 XML 不含命名空间,可直接用 findall('url') 等方式查找节点。
很多 XML 文档使用默认命名空间(如 xmlns="..."),这会导致直接查找失败。解决方法是:
.//{*}loc 表示忽略命名空间查找 loc 标签
for loc in root.findall('.//{*}loc'):
print(loc.text)
这种写法更灵活,适用于不确定命名空间的情况。
可以将提取的数据保存为 CSV、JSON 或数据库,便于后续分析。
保存为 CSV 示例:
import csv
<p>with open('urls.csv', 'w', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
writer.writerow(['URL', 'Last Modified'])
for url in root.findall('ns:url', namespaces):
loc = url.find('ns:loc', namespaces).text
lastmod = url.find('ns:lastmod', namespaces).text
writer.writerow([loc, lastmod])</p>基本上就这些。只要目标网站允许访问 XML 文件,整个过程不复杂但容易忽略命名空间和反爬机制。建议遵守 robots.txt,控制请求频率,避免对服务器造成压力。
以上就是如何从网页上抓取xml数据 网络爬虫爬取xml教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号