爬虫-BeautifulSoup之XML篇

1. 发送 HTTP 请求获取页面内容

python 复制代码
url = "https://example.com"
response = requests.get(url)
xml_content = response.text

2. 创建 Beautiful Soup 对象

python 复制代码
soup = BeautifulSoup(xml_content, 'xml')

3. 解析 XML 标签

3.1. 标签选择器

python 复制代码
# 选择所有的 <element> 标签
elements = soup.find_all('element')

# 选择第一个 <element> 标签
first_element = soup.find('element')

3.2. 属性选择器

python 复制代码
# 选择属性 id 为 '1' 的所有 <element> 标签
elements_with_id = soup.find_all('element', id='1')

4. 提取标签内容

python 复制代码
# 获取标签文本内容
first_element_content = first_element.text

5. 遍历标签集合

python 复制代码
for element in elements:
    print(element.text)

6. 使用 CSS 选择器

python 复制代码
# 通过 CSS 选择器选择所有 <element> 标签
elements_css = soup.select('element')

7. 处理嵌套标签

python 复制代码
# 获取嵌套标签的内容
nested_content = soup.select_one('root element').text

8. 提取嵌套标签的内容

python 复制代码
# 嵌套选择标签
nested_element_content = soup.find('root').find('element').text

9. 使用 find_all 方法

python 复制代码
# 使用 `find_all` 方法选择属性 id 为 "1" 的所有 <element> 标签
elements_with_id = soup.find_all("element", attrs={"id": "1"})
相关推荐
Flittly3 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(3)TodoWrite (待办写入)
python·agent
千寻girling8 小时前
一份不可多得的 《 Django 》 零基础入门教程
后端·python·面试
databook11 小时前
探索视觉的边界:用 Manim 重现有趣的知觉错觉
python·动效
明月_清风12 小时前
Python 性能微观世界:列表推导式 vs for 循环
后端·python
明月_清风12 小时前
Python 性能翻身仗:从 O(n) 到 O(1) 的工程实践
后端·python
helloweilei1 天前
python 抽象基类
python
用户8356290780511 天前
Python 实现 PPT 转 HTML
后端·python
zone77391 天前
004:RAG 入门-LangChain读取PDF
后端·python·面试
zone77391 天前
005:RAG 入门-LangChain读取表格数据
后端·python·agent
树獭非懒2 天前
AI大模型小白手册|Embedding 与向量数据库
后端·python·llm