寒假打卡21-2月7日

HTML 解析与数据提取

在本篇文章中,我们将介绍如何使用 Python 解析 HTML 并提取数据。我们将使用 BeautifulSouplxml 库,这些库提供了强大的 HTML 解析和数据提取功能。此外,我们还将介绍如何使用正则表达式和 XPath 提取数据。

1. 安装所需库

首先,我们需要安装 BeautifulSouplxml 库。可以使用以下命令通过 pip 安装:

pip install beautifulsoup4 lxml

2. 使用 BeautifulSoup 解析 HTML

基本用法

使用 BeautifulSoup 解析 HTML 文档。

from bs4 import BeautifulSoup

html_doc = """
<html>
<head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
</body>
</html>
"""

soup = BeautifulSoup(html_doc, 'lxml')
print(soup.prettify())

查找元素

使用 findfind_all 方法查找元素。

# 查找第一个 <p> 元素
p = soup.find('p')
print(p)  # 输出: <p class="title"><b>The Dormouse's story</b></p>

# 查找所有 <a> 元素
a_tags = soup.find_all('a')
for a in a_tags:
    print(a['href'])  # 输出: 链接地址

获取属性和文本

使用 get 方法获取属性,使用 text 属性获取元素文本。

# 获取第一个 <a> 元素的 href 属性
a = soup.find('a')
print(a.get('href'))  # 输出: http://example.com/elsie

# 获取第一个 <p> 元素的文本
p = soup.find('p')
print(p.text)  # 输出: The Dormouse's story

3. 使用 lxml 解析 XML

基本用法

使用 lxml 解析 XML 文档。

from lxml import etree

xml_doc = """
<root>
  <child name="child1">Child 1</child>
  <child name="child2">Child 2</child>
  <child name="child3">Child 3</child>
</root>
"""

root = etree.fromstring(xml_doc)
print(etree.tostring(root, pretty_print=True).decode())

查找元素

使用 XPath 查找元素。

# 查找第一个 <child> 元素
child = root.xpath('//child')[0]
print(child.text)  # 输出: Child 1

# 查找所有 <child> 元素的 name 属性
names = root.xpath('//child/@name')
print(names)  # 输出: ['child1', 'child2', 'child3']

4. 使用正则表达式提取数据

基本用法

使用 re 模块处理正则表达式。

import re

text = "The price of the book is $29.99."
pattern = r'\$\d+\.\d{2}'

match = re.search(pattern, text)
if match:
    print(match.group())  # 输出: $29.99

从 HTML 中提取数据

结合 BeautifulSoup 和正则表达式提取数据。

html_doc = """
<html>
<body>
<p class="price">$29.99</p>
<p class="price">$19.99</p>
</body>
</html>
"""

soup = BeautifulSoup(html_doc, 'lxml')
prices = soup.find_all('p', class_='price')

pattern = r'\$\d+\.\d{2}'
for price in prices:
    match = re.search(pattern, price.text)
    if match:
        print(match.group())  # 输出: $29.99 和 $19.99

5. 使用 XPath 提取数据

基本用法

使用 lxml 的 XPath 提取数据。

from lxml import etree

html_doc = """
<html>
<body>
<p class="price">$29.99</p>
<p class="price">$19.99</p>
</body>
</html>
"""

tree = etree.HTML(html_doc)
prices = tree.xpath('//p[@class="price"]/text()')
for price in prices:
    print(price)  # 输出: $29.99 和 $19.99

总结

在本篇文章中,我们介绍了如何使用 Python 解析 HTML 并提取数据,包括使用 BeautifulSouplxml 解析 HTML 和 XML 文档,使用正则表达式和 XPath 提取数据。通过掌握这些知识,你能够从 Web 页面中提取所需的数据,为后续的数据处理和分析打下基础。接下来,我们将探讨 Scrapy 爬虫框架的相关内容,敬请期待!

posted @ 2025-02-07 09:11  aallofitisst  阅读(27)  评论(0)    收藏  举报