Python ET.parse 模塊功能詳解
什么是 ElementTree
xml.etree.ElementTree(通常簡稱為 ET)是 Python 標(biāo)準(zhǔn)庫中用于解析和創(chuàng)建 XML 數(shù)據(jù)的模塊。它提供了輕量級、高效的 API,適合處理小到中等規(guī)模的 XML 文檔。
為什么選擇 ET?
- ? Python 內(nèi)置,無需安裝
- ? 簡單易用的 API 設(shè)計
- ? 內(nèi)存效率高(迭代解析)
- ? 支持 XPath 表達(dá)式查找元素
基礎(chǔ)概念:XML 結(jié)構(gòu)
在深入學(xué)習(xí)之前,先了解 XML 的基本結(jié)構(gòu):
<?xml version="1.0" encoding="UTF-8"?>
<!-- 這是注釋 -->
<library> <!-- 根元素 -->
<book id="001"> <!-- 元素 + 屬性 -->
<title>Python編程</title> <!-- 子元素 -->
<author>張三</author>
<price>59.00</price>
</book>
</library>核心概念:
- Element(元素):XML 標(biāo)簽,如
<book> - Tag(標(biāo)簽名):元素的名稱,如
"book" - Attribute(屬性):元素的特征,如
id="001" - Text(文本內(nèi)容):元素內(nèi)的文本,如
"Python編程" - Tail(尾部文本):結(jié)束標(biāo)簽后的文本(較少使用)
解析 XML 文件
1. 基本解析方法
ET 提供了兩種主要解析方式:
import xml.etree.ElementTree as ET
# 方法1:解析文件(推薦用于文件)
tree = ET.parse('books.xml') # 返回 ElementTree 對象
root = tree.getroot() # 獲取根元素
# 方法2:解析字符串(用于從網(wǎng)絡(luò)或內(nèi)存讀?。?
xml_string = """<?xml version="1.0"?>
<library>
<book id="001">
<title>Python編程</title>
</book>
</library>"""
root = ET.fromstring(xml_string) # 直接返回根元素2. 完整解析示例
假設(shè)我們有如下 books.xml 文件:
<?xml version="1.0" encoding="UTF-8"?>
<library location="北京">
<book id="001" category="編程">
<title>Python編程:從入門到實踐</title>
<author>埃里克·馬瑟斯</author>
<price currency="CNY">89.00</price>
<publish_date>2020-05</publish_date>
</book>
<book id="002" category="小說">
<title>百年孤獨</title>
<author>加西亞·馬爾克斯</author>
<price currency="CNY">55.00</price>
<publish_date>2011-06</publish_date>
</book>
<book id="003" category="編程">
<title>流暢的Python</title>
<author>盧西亞諾·拉馬略</author>
<price currency="CNY">139.00</price>
<publish_date>2017-05</publish_date>
</book>
</library>解析代碼:
import xml.etree.ElementTree as ET
def parse_library():
"""解析圖書館 XML 文件"""
try:
# 解析 XML 文件
tree = ET.parse('books.xml')
root = tree.getroot()
print(f"根元素標(biāo)簽: {root.tag}")
print(f"根元素屬性: {root.attrib}")
print(f"子元素數(shù)量: {len(root)}")
print("-" * 50)
# 遍歷所有 book 元素
for book in root.findall('book'):
book_id = book.get('id') # 獲取屬性
category = book.get('category')
title = book.find('title').text # 獲取文本內(nèi)容
author = book.find('author').text
price_elem = book.find('price')
price = price_elem.text
currency = price_elem.get('currency')
print(f"圖書ID: {book_id}")
print(f"類別: {category}")
print(f"書名: {title}")
print(f"作者: {author}")
print(f"價格: {currency} {price}")
print("-" * 50)
except ET.ParseError as e:
print(f"XML 解析錯誤: {e}")
except FileNotFoundError:
print("文件未找到,請確保 books.xml 存在")
if __name__ == "__main__":
parse_library()輸出結(jié)果:
根元素標(biāo)簽: library
根元素屬性: {'location': '北京'}
子元素數(shù)量: 3
--------------------------------------------------
圖書ID: 001
類別: 編程
書名: Python編程:從入門到實踐
作者: 埃里克·馬瑟斯
價格: CNY 89.00
--------------------------------------------------
...
遍歷 XML 樹
1. 迭代遍歷(內(nèi)存友好)
對于大型 XML 文件,使用迭代器避免一次性加載所有數(shù)據(jù):
import xml.etree.ElementTree as ET
def iterate_xml():
"""使用迭代器遍歷大型 XML"""
# iterparse 在解析時生成事件,適合大文件
context = ET.iterparse('books.xml', events=('start', 'end'))
context = iter(context)
event, root = next(context)
book_count = 0
for event, elem in context:
# 'start' 事件:元素開始
# 'end' 事件:元素結(jié)束(此時元素已完整)
if event == 'end' and elem.tag == 'book':
book_count += 1
title = elem.find('title').text
print(f"處理第 {book_count} 本書: {title}")
# 處理完后清除元素釋放內(nèi)存
elem.clear()
root.clear()
print(f"總共處理了 {book_count} 本書")
# 遞歸遍歷所有元素
def recursive_walk(element, level=0):
"""遞歸打印 XML 結(jié)構(gòu)"""
indent = " " * level
print(f"{indent}<{element.tag}> {element.attrib if element.attrib else ''}")
if element.text and element.text.strip():
print(f"{indent} 文本: {element.text.strip()}")
for child in element:
recursive_walk(child, level + 1)
print(f"{indent}</{element.tag}>")
# 使用示例
tree = ET.parse('books.xml')
recursive_walk(tree.getroot())2. 按層級遍歷
def traverse_by_level(root):
"""按層級遍歷(廣度優(yōu)先)"""
from collections import deque
queue = deque([(root, 0)])
while queue:
elem, level = queue.popleft()
indent = " " * level
print(f"{indent}[{level}] {elem.tag}: {elem.attrib}")
for child in elem:
queue.append((child, level + 1))
traverse_by_level(tree.getroot())查找元素
ET 支持有限的 XPath 表達(dá)式,非常實用:
import xml.etree.ElementTree as ET
tree = ET.parse('books.xml')
root = tree.getroot()
# 1. find() - 查找第一個匹配的直接子元素
first_book = root.find('book')
print(f"第一本書: {first_book.find('title').text}")
# 2. findall() - 查找所有匹配的直接子元素
all_books = root.findall('book')
print(f"圖書總數(shù): {len(all_books)}")
# 3. iter() - 遞歸查找所有指定標(biāo)簽
all_prices = root.iter('price')
print("所有價格:")
for price in all_prices:
print(f" {price.text} {price.get('currency')}")
# 4. 帶條件的查找(XPath 語法)
# 查找 category="編程" 的所有圖書
programming_books = root.findall(".//book[@category='編程']")
print(f"\n編程類圖書數(shù)量: {len(programming_books)}")
# 5. 復(fù)雜 XPath 示例
# 查找價格大于 100 的圖書(需要遍歷判斷)
expensive_books = []
for book in root.findall('book'):
price = float(book.find('price').text)
if price > 100:
expensive_books.append(book.find('title').text)
print(f"高價圖書: {expensive_books}")
# 6. 查找特定路徑
# 查找第一個 book 下的 title
title = root.find('./book[1]/title')
print(f"第一本書書名: {title.text}")支持的 XPath 語法:
| 語法 | 說明 |
|---|---|
tag | 選擇直接子元素 |
* | 匹配所有子元素 |
. | 當(dāng)前元素 |
// | 遞歸查找所有后代 |
.. | 父元素 |
[@attrib] | 有某屬性的元素 |
[@attrib='value'] | 屬性等于某值的元素 |
[tag] | 有某子元素的元素 |
[position] | 第 N 個元素(從1開始) |
獲取元素數(shù)據(jù)
完整的數(shù)據(jù)提取工具類
import xml.etree.ElementTree as ET
from dataclasses import dataclass
from typing import List, Optional, Dict
@dataclass
class Book:
"""圖書數(shù)據(jù)類"""
id: str
category: str
title: str
author: str
price: float
currency: str
publish_date: str
class XMLExtractor:
"""XML 數(shù)據(jù)提取器"""
def __init__(self, xml_file: str):
self.tree = ET.parse(xml_file)
self.root = self.tree.getroot()
def get_root_info(self) -> Dict:
"""獲取根元素信息"""
return {
'tag': self.root.tag,
'attributes': dict(self.root.attrib),
'children_count': len(self.root)
}
def extract_all_books(self) -> List[Book]:
"""提取所有圖書信息"""
books = []
for book_elem in self.root.findall('book'):
book = Book(
id=book_elem.get('id', ''),
category=book_elem.get('category', ''),
title=self._get_text(book_elem, 'title'),
author=self._get_text(book_elem, 'author'),
price=float(self._get_text(book_elem, 'price')),
currency=book_elem.find('price').get('currency', 'CNY'),
publish_date=self._get_text(book_elem, 'publish_date')
)
books.append(book)
return books
def _get_text(self, parent: ET.Element, tag: str, default: str = '') -> str:
"""安全獲取子元素文本"""
elem = parent.find(tag)
return elem.text if elem is not None else default
def get_books_by_category(self, category: str) -> List[Dict]:
"""按類別篩選圖書"""
results = []
xpath = f".//book[@category='{category}']"
for book in self.root.findall(xpath):
results.append({
'id': book.get('id'),
'title': book.find('title').text,
'author': book.find('author').text
})
return results
def get_statistics(self) -> Dict:
"""獲取統(tǒng)計信息"""
books = self.extract_all_books()
if not books:
return {}
prices = [b.price for b in books]
categories = {}
for b in books:
categories[b.category] = categories.get(b.category, 0) + 1
return {
'total_books': len(books),
'avg_price': sum(prices) / len(prices),
'max_price': max(prices),
'min_price': min(prices),
'categories': categories
}
# 使用示例
if __name__ == "__main__":
extractor = XMLExtractor('books.xml')
print("=== 根元素信息 ===")
print(extractor.get_root_info())
print("\n=== 所有圖書 ===")
for book in extractor.extract_all_books():
print(f"{book.id}: {book.title} ({book.author}) - {book.currency}{book.price}")
print("\n=== 編程類圖書 ===")
print(extractor.get_books_by_category('編程'))
print("\n=== 統(tǒng)計信息 ===")
stats = extractor.get_statistics()
print(f"圖書總數(shù): {stats['total_books']}")
print(f"平均價格: ¥{stats['avg_price']:.2f}")
print(f"價格區(qū)間: ¥{stats['min_price']:.2f} - ¥{stats['max_price']:.2f}")
print(f"類別分布: {stats['categories']}")修改 XML
1. 修改現(xiàn)有元素
import xml.etree.ElementTree as ET
def modify_xml():
"""修改 XML 內(nèi)容"""
tree = ET.parse('books.xml')
root = tree.getroot()
# 1. 修改屬性
root.set('updated', '2024-01-01')
root.set('location', '上海') # 修改現(xiàn)有屬性
# 2. 修改元素文本
for book in root.findall('book'):
price_elem = book.find('price')
old_price = float(price_elem.text)
# 打 8 折
new_price = old_price * 0.8
price_elem.text = f"{new_price:.2f}"
price_elem.set('discount', '0.8')
# 3. 添加新元素
for book in root.findall('book'):
stock = ET.SubElement(book, 'stock')
stock.text = '100'
stock.set('warehouse', 'A1')
# 4. 刪除元素
# 刪除第一本書的 publish_date
first_book = root.find('book')
publish_date = first_book.find('publish_date')
if publish_date is not None:
first_book.remove(publish_date)
# 5. 保存修改
tree.write('books_modified.xml',
encoding='utf-8',
xml_declaration=True,
short_empty_elements=False)
print("修改完成,已保存到 books_modified.xml")
modify_xml()2. 批量修改工具
class XMLModifier:
"""XML 批量修改器"""
def __init__(self, input_file: str):
self.tree = ET.parse(input_file)
self.root = self.tree.getroot()
self.modified = False
def update_prices(self, increase_rate: float = 0.1):
"""批量更新價格"""
for price_elem in self.root.iter('price'):
old_price = float(price_elem.text)
new_price = old_price * (1 + increase_rate)
price_elem.text = f"{new_price:.2f}"
price_elem.set('updated', 'true')
self.modified = True
print(f"已更新所有價格,漲幅 {increase_rate*100}%")
def add_element_to_all(self, tag: str, text: str, attrib: dict = None):
"""為所有 book 添加子元素"""
attrib = attrib or {}
for book in self.root.findall('book'):
elem = ET.SubElement(book, tag, attrib)
elem.text = text
self.modified = True
print(f"已為所有圖書添加 <{tag}> 元素")
def remove_element_by_tag(self, tag: str):
"""刪除所有指定標(biāo)簽的元素"""
count = 0
for parent in self.root.iter():
for child in list(parent): # 使用 list 避免迭代時修改
if child.tag == tag:
parent.remove(child)
count += 1
self.modified = True
print(f"已刪除 {count} 個 <{tag}> 元素")
def save(self, output_file: str = None):
"""保存文件"""
if not self.modified:
print("沒有修改需要保存")
return
output = output_file or 'modified.xml'
self.tree.write(output,
encoding='utf-8',
xml_declaration=True)
print(f"已保存到: {output}")
# 使用示例
modifier = XMLModifier('books.xml')
modifier.update_prices(0.15) # 漲價 15%
modifier.add_element_to_all('status', '在售', {'available': 'true'})
modifier.save('books_updated.xml')創(chuàng)建 XML
1. 從零創(chuàng)建 XML
import xml.etree.ElementTree as ET
from datetime import datetime
def create_library_xml():
"""創(chuàng)建圖書館 XML 文件"""
# 創(chuàng)建根元素
root = ET.Element('library')
root.set('version', '1.0')
root.set('created', datetime.now().isoformat())
# 添加注釋
comment = ET.Comment(' 這是一個自動生成的圖書館數(shù)據(jù)文件 ')
root.append(comment)
# 創(chuàng)建圖書數(shù)據(jù)
books_data = [
{
'id': '004',
'category': '科幻',
'title': '三體',
'author': '劉慈欣',
'price': '98.00',
'currency': 'CNY',
'tags': ['雨果獎', '科幻經(jīng)典', '系列作品']
},
{
'id': '005',
'category': '技術(shù)',
'title': '深度學(xué)習(xí)',
'author': '伊恩·古德費洛',
'price': '168.00',
'currency': 'CNY',
'tags': ['AI', '機(jī)器學(xué)習(xí)', '教材']
}
]
for book_data in books_data:
# 創(chuàng)建 book 元素
book = ET.SubElement(root, 'book')
book.set('id', book_data['id'])
book.set('category', book_data['category'])
# 添加子元素
title = ET.SubElement(book, 'title')
title.text = book_data['title']
author = ET.SubElement(book, 'author')
author.text = book_data['author']
price = ET.SubElement(book, 'price')
price.text = book_data['price']
price.set('currency', book_data['currency'])
# 添加標(biāo)簽列表
tags = ET.SubElement(book, 'tags')
for tag_text in book_data['tags']:
tag = ET.SubElement(tags, 'tag')
tag.text = tag_text
# 創(chuàng)建 ElementTree 對象
tree = ET.ElementTree(root)
# 美化輸出(縮進(jìn))
ET.indent(tree, space=' ', level=0)
# 保存到文件
tree.write('new_library.xml',
encoding='utf-8',
xml_declaration=True,
short_empty_elements=False)
print("成功創(chuàng)建 new_library.xml")
# 同時返回字符串形式
return ET.tostring(root, encoding='unicode')
xml_string = create_library_xml()
print("\n生成的 XML 內(nèi)容:")
print(xml_string)生成的 XML 結(jié)構(gòu):
<?xml version='1.0' encoding='utf-8'?>
<library created="2024-01-15T10:30:00" version="1.0">
<!-- 這是一個自動生成的圖書館數(shù)據(jù)文件 -->
<book category="科幻" id="004">
<title>三體</title>
<author>劉慈欣</author>
<price currency="CNY">98.00</price>
<tags>
<tag>雨果獎</tag>
<tag>科幻經(jīng)典</tag>
<tag>系列作品</tag>
</tags>
</book>
...
</library>2. 使用 Element 工廠函數(shù)
def create_element_factory():
"""使用工廠模式創(chuàng)建 XML"""
def create_book(id, title, author, **kwargs):
"""創(chuàng)建圖書元素的工廠函數(shù)"""
book = ET.Element('book', {'id': id})
ET.SubElement(book, 'title').text = title
ET.SubElement(book, 'author').text = author
for key, value in kwargs.items():
if isinstance(value, dict):
# 帶屬性的元素
elem = ET.SubElement(book, key, value.get('attrib', {}))
elem.text = value.get('text', '')
else:
ET.SubElement(book, key).text = str(value)
return book
# 構(gòu)建 XML
root = ET.Element('catalog')
book1 = create_book(
'006',
'Python數(shù)據(jù)科學(xué)手冊',
'杰克·萬托布拉斯',
price={'text': '128.00', 'attrib': {'currency': 'CNY'}},
publisher='人民郵電出版社',
year='2020'
)
root.append(book1)
# 保存
tree = ET.ElementTree(root)
ET.indent(tree, space=' ')
tree.write('catalog.xml', encoding='utf-8', xml_declaration=True)
print("創(chuàng)建 catalog.xml 成功")
create_element_factory()實際應(yīng)用案例
案例1:配置文件管理器
import xml.etree.ElementTree as ET
import os
class ConfigManager:
"""XML 配置文件管理器"""
CONFIG_FILE = 'app_config.xml'
def __init__(self):
self.tree = None
self.root = None
self._load_or_create()
def _load_or_create(self):
"""加載或創(chuàng)建配置文件"""
if os.path.exists(self.CONFIG_FILE):
self.tree = ET.parse(self.CONFIG_FILE)
self.root = self.tree.getroot()
else:
self.root = ET.Element('configuration')
self.root.set('version', '1.0')
self.tree = ET.ElementTree(self.root)
self._save()
def _save(self):
"""保存配置"""
ET.indent(self.tree, space=' ')
self.tree.write(self.CONFIG_FILE, encoding='utf-8', xml_declaration=True)
def get(self, section: str, key: str, default=None):
"""獲取配置值"""
section_elem = self.root.find(f".//section[@name='{section}']")
if section_elem is None:
return default
item = section_elem.find(f"item[@key='{key}']")
if item is None:
return default
return item.get('value')
def set(self, section: str, key: str, value: str):
"""設(shè)置配置值"""
section_elem = self.root.find(f".//section[@name='{section}']")
if section_elem is None:
section_elem = ET.SubElement(self.root, 'section')
section_elem.set('name', section)
item = section_elem.find(f"item[@key='{key}']")
if item is None:
item = ET.SubElement(section_elem, 'item')
item.set('key', key)
item.set('value', str(value))
self._save()
def get_database_config(self) -> dict:
"""獲取數(shù)據(jù)庫配置"""
return {
'host': self.get('database', 'host', 'localhost'),
'port': int(self.get('database', 'port', '3306')),
'username': self.get('database', 'username', 'root'),
'password': self.get('database', 'password', ''),
'database': self.get('database', 'database', 'test')
}
# 使用示例
config = ConfigManager()
config.set('database', 'host', '192.168.1.100')
config.set('database', 'port', '5432')
config.set('app', 'debug', 'true')
print(config.get_database_config())案例2:數(shù)據(jù)轉(zhuǎn)換器(CSV 轉(zhuǎn) XML)
import csv
import xml.etree.ElementTree as ET
from datetime import datetime
def csv_to_xml(csv_file: str, xml_file: str, root_tag: str = 'data'):
"""將 CSV 文件轉(zhuǎn)換為 XML"""
root = ET.Element(root_tag)
root.set('generated', datetime.now().isoformat())
root.set('source', csv_file)
with open(csv_file, 'r', encoding='utf-8') as f:
reader = csv.DictReader(f)
for i, row in enumerate(reader, 1):
record = ET.SubElement(root, 'record')
record.set('id', str(i))
for key, value in row.items():
# 清理標(biāo)簽名(XML 標(biāo)簽不能以數(shù)字開頭,不能包含空格)
clean_key = key.strip().replace(' ', '_')
if clean_key[0].isdigit():
clean_key = 'f_' + clean_key
field = ET.SubElement(record, clean_key)
field.text = value
# 美化并保存
tree = ET.ElementTree(root)
ET.indent(tree, space=' ')
tree.write(xml_file, encoding='utf-8', xml_declaration=True)
print(f"成功轉(zhuǎn)換: {csv_file} -> {xml_file}")
# 示例 CSV 內(nèi)容:
# name,age,city
# 張三,28,北京
# 李四,32,上海
# csv_to_xml('data.csv', 'output.xml')常見錯誤與解決方案
1. 編碼問題
# ? 錯誤:默認(rèn)編碼可能不支持中文
tree.write('output.xml')
# ? 正確:指定 UTF-8 編碼
tree.write('output.xml', encoding='utf-8', xml_declaration=True)2. 命名空間處理
# 處理帶命名空間的 XML
xml_with_ns = """<?xml version="1.0"?>
<root xmlns:ns="http://example.com/ns">
<ns:item>內(nèi)容</ns:item>
</root>"""
root = ET.fromstring(xml_with_ns)
# 方法1:使用完整標(biāo)簽名
for elem in root.findall('{http://example.com/ns}item'):
print(elem.text)
# 方法2:定義命名空間字典
namespaces = {'ns': 'http://example.com/ns'}
for elem in root.findall('ns:item', namespaces):
print(elem.text)3. 大小寫敏感
# XML 是大小寫敏感的
root.find('Book') # 找不到 <book>
root.find('book') # 正確4. 內(nèi)存優(yōu)化
# 大文件處理(>100MB)
# ? 錯誤:一次性加載
tree = ET.parse('huge.xml')
# ? 正確:迭代解析
for event, elem in ET.iterparse('huge.xml', events=('end',)):
if elem.tag == 'record':
process(elem)
elem.clear() # 釋放內(nèi)存5. 特殊字符轉(zhuǎn)義
# ET 自動處理特殊字符
root = ET.Element('test')
root.text = '<特殊內(nèi)容> & "引號"'
# 輸出: <特殊內(nèi)容> & "引號"總結(jié)
| 功能 | 方法 | 說明 |
|---|---|---|
| 解析文件 | ET.parse() | 返回 ElementTree |
| 解析字符串 | ET.fromstring() | 返回根元素 |
| 查找單個 | element.find() | 第一個匹配 |
| 查找多個 | element.findall() | 所有直接子元素 |
| 遞歸查找 | element.iter() | 所有后代元素 |
| 獲取屬性 | element.get() | 獲取屬性值 |
| 獲取文本 | element.text | 元素內(nèi)容 |
| 創(chuàng)建子元素 | ET.SubElement() | 工廠函數(shù) |
| 保存文件 | tree.write() | 寫入文件 |
最佳實踐建議:
- 始終指定
encoding='utf-8'保存中文 - 大文件使用
iterparse()迭代處理 - 使用
try-except捕獲ParseError - 復(fù)雜查詢考慮使用
lxml庫(支持完整 XPath) - 修改前先備份原文件
通過本教程的學(xué)習(xí),您已經(jīng)掌握了 Python ET 模塊的核心功能,可以處理絕大多數(shù) XML 數(shù)據(jù)操作需求。建議動手實踐每個示例代碼,加深理解。
到此這篇關(guān)于Python ET.parse 模塊功能詳解的文章就介紹到這了,更多相關(guān)Python ET.parse內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python?DataFrame中stack()方法、unstack()方法和pivot()方法淺析
這篇文章主要給大家介紹了關(guān)于python?DataFrame中stack()方法、unstack()方法和pivot()方法的相關(guān)資料,pandas中這三種方法都是用來對表格進(jìn)行重排的,其中stack()是unstack()的逆操作,需要的朋友可以參考下2022-04-04
python實現(xiàn)一行輸入多個值和一行輸出多個值的例子
今天小編就為大家分享一篇python實現(xiàn)一行輸入多個值和一行輸出多個值的例子,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-07-07
在pytorch中計算準(zhǔn)確率,召回率和F1值的操作
這篇文章主要介紹了在pytorch中計算準(zhǔn)確率,召回率和F1值的操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-05-05
Python簡單實現(xiàn)安全開關(guān)文件的兩種方式
這篇文章主要介紹了Python簡單實現(xiàn)安全開關(guān)文件的兩種方式,涉及Python的try語句針對錯誤的判定與捕捉相關(guān)技巧,需要的朋友可以參考下2016-09-09
一文教你徹底掌握Python數(shù)據(jù)類型轉(zhuǎn)換
Python的核心數(shù)據(jù)類型包括:int(整數(shù)),float(浮點數(shù)),str(字符串),bool(布爾值),本文整理了他們之前相互轉(zhuǎn)換的方法,需要的可以了解下2025-05-05
利用Python抓取網(wǎng)頁數(shù)據(jù)的多種方式與示例詳解
在數(shù)據(jù)科學(xué)和網(wǎng)絡(luò)爬蟲領(lǐng)域,網(wǎng)頁數(shù)據(jù)抓取是非常重要的一項技能,Python 是進(jìn)行網(wǎng)頁抓取的流行語言,因為它擁有強(qiáng)大的第三方庫,能夠簡化網(wǎng)頁解析和數(shù)據(jù)提取的過程,本篇文章將介紹幾種常見的網(wǎng)頁數(shù)據(jù)抓取方法,需要的朋友可以參考下2025-04-04

