从HTML网页抓取数据并映射成XML是数据清洗和格式转换场景中的常见需求,核心流程分为网页内容获取、HTML解析提取目标数据、XML结构构建与输出三个环节,下面将通过Python语言实现完整的处理逻辑。

一、核心依赖工具准备
实现该功能需要用到三个核心Python库:requests用于发送HTTP请求获取网页内容,BeautifulSoup用于解析HTML结构提取数据,xml.etree.ElementTree用于构建和输出XML文件。如果本地未安装前两个库,可以通过pip命令安装:
# 安装依赖库 pip install requests beautifulsoup4
二、HTML网页数据抓取
首先需要通过HTTP请求获取目标网页的HTML内容,这里以抓取一个模拟的商品列表页面为例,先实现网页内容的获取功能:
import requests
def fetch_html(url):
# 设置请求头模拟浏览器访问,避免被部分网站拦截
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
}
try:
response = requests.get(url, headers=headers, timeout=10)
# 设置正确的编码,避免中文乱码
response.encoding = response.apparent_encoding
return response.text
except Exception as e:
print(f"获取网页内容失败: {e}")
return None
# 测试获取网页内容,这里使用本地模拟的HTML内容代替实际请求
test_html = """
<html>
<body>
<div class="product-list">
<div class="product">
<span class="name">无线鼠标</span>
<span class="price">89.9</span>
<span class="stock">200</span>
</div>
<div class="product">
<span class="name">机械键盘</span>
<span class="price">299.0</span>
<span class="stock">150</span>
</div>
</div>
</body>
</html>
"""
三、解析HTML提取目标数据
获取到HTML内容后,使用BeautifulSoup解析结构,定位到目标数据所在的标签,提取出需要的字段内容:
from bs4 import BeautifulSoup
def parse_html_to_data(html_content):
# 创建BeautifulSoup对象,使用html.parser解析器
soup = BeautifulSoup(html_content, "html.parser")
# 定位所有商品所在的div标签
product_divs = soup.find_all("div", class_="product")
product_list = []
for div in product_divs:
# 提取每个商品的名称、价格、库存字段
name = div.find("span", class_="name").text.strip()
price = div.find("span", class_="price").text.strip()
stock = div.find("span", class_="stock").text.strip()
product_list.append({
"name": name,
"price": price,
"stock": stock
})
return product_list
# 测试解析功能
if test_html:
products = parse_html_to_data(test_html)
print("提取到的商品数据:", products)
四、数据映射生成XML文件
提取到结构化数据后,使用xml.etree.ElementTree库按照XML的层级结构构建节点,将映射规则写入XML文件:
import xml.etree.ElementTree as ET
def map_data_to_xml(product_list, output_path):
# 创建根节点
root = ET.Element("products")
# 遍历商品数据,为每个商品创建子节点
for item in product_list:
product_node = ET.SubElement(root, "product")
# 创建商品下的子节点,对应提取的字段
name_node = ET.SubElement(product_node, "name")
name_node.text = item["name"]
price_node = ET.SubElement(product_node, "price")
price_node.text = item["price"]
stock_node = ET.SubElement(product_node, "stock")
stock_node.text = item["stock"]
# 创建ElementTree对象
tree = ET.ElementTree(root)
# 写入XML文件,设置编码为utf-8,添加xml声明
tree.write(output_path, encoding="utf-8", xml_declaration=True)
print(f"XML文件已生成,路径: {output_path}")
# 测试生成XML
if test_html:
products = parse_html_to_data(test_html)
map_data_to_xml(products, "product_list.xml")
五、完整流程整合
将上述步骤整合为完整的可执行脚本,实现从HTML抓取到XML输出的全流程:
import requests
from bs4 import BeautifulSoup
import xml.etree.ElementTree as ET
def fetch_html(url):
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
}
try:
response = requests.get(url, headers=headers, timeout=10)
response.encoding = response.apparent_encoding
return response.text
except Exception as e:
print(f"获取网页内容失败: {e}")
return None
def parse_html_to_data(html_content):
soup = BeautifulSoup(html_content, "html.parser")
product_divs = soup.find_all("div", class_="product")
product_list = []
for div in product_divs:
name = div.find("span", class_="name").text.strip()
price = div.find("span", class_="price").text.strip()
stock = div.find("span", class_="stock").text.strip()
product_list.append({
"name": name,
"price": price,
"stock": stock
})
return product_list
def map_data_to_xml(product_list, output_path):
root = ET.Element("products")
for item in product_list:
product_node = ET.SubElement(root, "product")
name_node = ET.SubElement(product_node, "name")
name_node.text = item["name"]
price_node = ET.SubElement(product_node, "price")
price_node.text = item["price"]
stock_node = ET.SubElement(product_node, "stock")
stock_node.text = item["stock"]
tree = ET.ElementTree(root)
tree.write(output_path, encoding="utf-8", xml_declaration=True)
print(f"XML文件已生成,路径: {output_path}")
if __name__ == "__main__":
# 实际使用时替换为目标网页URL,这里使用本地HTML测试
target_url = "http://ipipp.com/test.html"
html_content = fetch_html(target_url)
if html_content:
product_data = parse_html_to_data(html_content)
if product_data:
map_data_to_xml(product_data, "output.xml")
六、注意事项
- 抓取网页时需要遵守目标网站的robots协议,避免频繁请求给服务器造成压力
- 如果HTML结构较为复杂,需要根据实际的标签层级调整解析的定位逻辑,可通过浏览器的开发者工具查看网页结构
- 生成的XML字段可以根据实际需求调整,映射规则需要和下游使用XML的系统保持一致
- 部分网页内容是通过JavaScript动态渲染的,使用requests直接获取无法拿到动态内容,这种情况需要结合selenium等工具处理
网页数据抓取HTML解析XML映射BeautifulSoupPython修改时间:2026-06-30 23:00:44