1. HTML树的导航
今天我们将沉浸在HTML树的神秘世界中,学习如何像真正的编程忍者一样从网页中提取信息。我们将继续使用神奇的BeautifulSoup库,来获取需要的数据并给我们的超级聪明的脚本添加更多功能。所以,准备好你的键盘,我们开始吧!
那么,在提取数据之前,我们再来搞清楚什么是HTML树。想象一下,这就像一棵巨大的家谱树,每个标签是一个单独的亲戚。有父母、孩子、兄弟姐妹。我们的任务就是找到特定的“亲戚”,以便小心地从他们那里提取有价值的家族遗产(或者数据)。
下面是一个HTML片段:
<div class="article">
<h2 id="title">标题</h2>
<p class="content">这是文章文本...</p>
<a href="https://example.com" class="link">继续阅读</a>
</div>
这里我们有一个div,它是h2、p和a的父元素。每个都有自己的属性和内容。
2. 通过标签提取数据
BeautifulSoup提供了方便的方法来导航树并提取数据。我们从基础方法find()开始,它允许我们找到某个标签的第一个元素。而find_all()就像搜索的推土机,可以找到所有元素。
from bs4 import BeautifulSoup
html_doc = """<div class="article">
<h2 id="title">标题</h2>
<p class="content">这是文章文本...</p>
<a href="https://example.com" class="link">继续阅读</a>
</div>"""
soup = BeautifulSoup(html_doc, 'html.parser')
# 找到第一个段落
first_paragraph = soup.find('p')
print(first_paragraph.text) # 输出: 这是文章文本...
# 找到所有链接
all_links = soup.find_all('a')
for link in all_links:
print(link['href']) # 输出: https://example.com
3. 使用属性过滤元素
现在当我们掌握了通过标签搜索的方法,是时候学习如何使用属性(如id和class)来过滤元素了。这些属性就像页面上的书签,看一眼便知是什么。
<div class="article">
<h2 id="title">标题</h2>
<p class="content">这是文章文本...</p>
<a href="https://example.com" class="link">继续阅读</a>
</div>
# 找到具有特定id的元素
title = soup.find(id="title")
print(title.text) # 输出: 标题
# 找到所有带有"class=content"的元素
content_paragraphs = soup.find_all(class_="content")
for p in content_paragraphs:
print(p.text) # 输出: 这是文章文本...
重要! 我们使用class_而不是class,以避免与Python的保留关键字冲突。
4. 带条件的数据提取练习
现在开始实战了!假设你需要从一个重复的HTML数组中提取文章的链接和标题。以下是数据示例及其操作方法:
<div class="articles">
<div class="article">
<h2 class="title">第一篇文章</h2>
<a href="https://example.com/1" class="read-more">继续阅读</a>
</div>
<div class="article">
<h2 class="title">第二篇文章</h2>
<a href="https://example.com/2" class="read-more">继续阅读</a>
</div>
</div>
下面是提取标题和链接的方法:
html_doc = """<div class="articles">
<div class="article">
<h2 class="title">第一篇文章</h2>
<a href="https://example.com/1" class="read-more">继续阅读</a>
</div>
<div class="article">
<h2 class="title">第二篇文章</h2>
<a href="https://example.com/2" class="read-more">继续阅读</a>
</div>
</div>"""
soup = BeautifulSoup(html_doc, 'html.parser')
articles = soup.find_all('div', class_='article')
for article in articles:
title = article.find('h2', class_='title').text
link = article.find('a', class_='read-more')['href']
print(f"标题: {title}, 链接: {link}")
# 输出:
# 标题: 第一篇文章, 链接: https://example.com/1
# 标题: 第二篇文章, 链接: https://example.com/2
5. 潜在问题
现在你已经掌握了知识,让我们看看一些常见的错误。其中一个最常见的问题是试图访问不存在的属性。Python会用友好的但仍然令人不快的KeyError来响应。为了避免这种情况,可以使用方法.get()在缺少属性时获得默认值。
此外,不要忘记HTML元素可能嵌套并具有复杂的结构。使用浏览器的页面源码查看工具来确保正确理解结构,然后再试图使用BeautifulSoup提取数据。
我们下一步的冒险将是使用CSS选择器以更精确地定位和提取信息。所以请继续关注,因为BeautifulSoup的世界才刚刚开始!
GO TO FULL VERSION