0Pricing
AI Agents · 课时

使用 BeautifulSoup 解析 HTML

find()、select()、CSS 选择器,以及从 HTML 中提取结构化内容。

使用 BeautifulSoup 解析 HTML 是 CoddyKit 上的免费 AI Agents 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 AI Agents 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 AI Agents 课程共包含 4 节课。

为什么智能体需要解析 HTML

许多数据源并不是 API,而是网页。当智能体需要从 HTML 中提取结构化信息时,必须将原始标记解析为可导航的树。

BeautifulSoup(bs4)是用于此目的的标准 Python 库。它会将杂乱的 HTML 转换为易于查询的 Python 对象。

创建 BeautifulSoup 对象

将原始 HTML 和解析器名称传递给 BeautifulSoup()。'html.parser' 内置于 Python 中,无需额外安装。若要更快地解析大型页面,可以通过 pip 使用 'lxml'。

from bs4 import BeautifulSoup
import httpx

# Fetch HTML
response = httpx.get('https://example.com', timeout=10.0)
html = response.text

# Parse it
soup = BeautifulSoup(html, 'html.parser')

# Get the page title
print(soup.title.text)  # 'Example Domain'

find() — 查找单个元素

soup.find(tag, attrs) 返回第一个匹配的元素;如果未找到,则返回 None。您可以根据标签名称、类、ID 或任意属性进行匹配。

对结果调用方法前,请始终检查它是否为 None。

from bs4 import BeautifulSoup

html = '<div class="content"><h1>Title</h1><p>Body text here.</p></div>'
soup = BeautifulSoup(html, 'html.parser')

# Find by tag + class
content_div = soup.find('div', class_='content')
if content_div:
    heading = content_div.find('h1')
    print(heading.text)  # 'Title'

# Find by id
sidebar = soup.find('div', id='sidebar')  # None if absent

find_all() — 查找多个元素

soup.find_all(tag) 返回所有匹配元素组成的列表。请遍历该列表,从列表项、表格行或文章卡片等重复结构中提取数据。

from bs4 import BeautifulSoup

html = '<ul><li>Apple</li><li>Banana</li><li>Cherry</li></ul>'
soup = BeautifulSoup(html, 'html.parser')

items = soup.find_all('li')
for item in items:
    print(item.text)  # Apple, Banana, Cherry

# Limit results
first_two = soup.find_all('li', limit=2)

使用 select() 进行 CSS 选择

soup.select('css selector') 允许您使用熟悉的 CSS 语法。与链式 find() 调用相比,这种方式通常更加简洁,尤其适用于嵌套元素。

from bs4 import BeautifulSoup

html = '''
<table>
  <tr><td class="name">Alice</td><td class="score">95</td></tr>
  <tr><td class="name">Bob</td><td class="score">87</td></tr>
</table>
'''
soup = BeautifulSoup(html, 'html.parser')

# Select all td elements inside tr inside table
cells = soup.select('table tr td')
for cell in cells:
    print(cell.text)

# Select only name cells
names = soup.select('td.name')
for n in names:
    print(n.text)  # Alice, Bob

使用 .text 和 .strip() 提取文本

.text(或 .get_text())返回元素内的全部文本内容,包括嵌套标签中的文本。请使用 .strip() 删除开头和结尾的空白,因为 HTML 中经常包含这类空白。

from bs4 import BeautifulSoup

html = '<p>  \n  Price: <strong>$29.99</strong>  \n  </p>'
soup = BeautifulSoup(html, 'html.parser')

paragraph = soup.find('p')

# .text includes nested tag content
print(paragraph.text)          # '  \n  Price: $29.99  \n  '
print(paragraph.text.strip())  # 'Price: $29.99'

# get_text with separator
print(paragraph.get_text(separator=' ', strip=True))  # 'Price: $29.99'

使用 .get() 提取属性

可以像访问字典一样,通过 .get('attr_name') 访问标签属性,例如 href、src 和 data-*。如果属性不存在,该方法会安全地返回 None。

from bs4 import BeautifulSoup

html = '''
<a href="https://example.com/page" data-id="42">Click here</a>
<img src="/images/logo.png" alt="Logo">
'''
soup = BeautifulSoup(html, 'html.parser')

link = soup.find('a')
print(link.get('href'))     # 'https://example.com/page'
print(link.get('data-id'))  # '42'
print(link.get('class'))    # None (no class attribute)

img = soup.find('img')
print(img.get('src'))       # '/images/logo.png'

浏览解析树

BeautifulSoup 元素之间存在父级、子级和同级关系,您可以沿这些关系进行遍历。使用 .parent、.children、.next_sibling 和 .previous_sibling 在已找到的元素周围进行导航。

from bs4 import BeautifulSoup

html = '''
<div class="article">
  <h2>Headline</h2>
  <p>First paragraph.</p>
  <p>Second paragraph.</p>
</div>
'''
soup = BeautifulSoup(html, 'html.parser')

h2 = soup.find('h2')
print(h2.text)                    # 'Headline'
print(h2.parent['class'])         # ['article']
print(h2.next_sibling.next_sibling.text)  # 'First paragraph.'

从页面提取所有链接

智能体的一项常见任务是收集页面中的所有链接,以便进一步抓取。请查找所有 <a> 标签并提取其 href 属性,同时过滤掉空链接。

from bs4 import BeautifulSoup
import httpx

def extract_links(url: str) -> list:
    response = httpx.get(url, timeout=10.0)
    soup = BeautifulSoup(response.text, 'html.parser')

    links = []
    for tag in soup.find_all('a'):
        href = tag.get('href')
        if href and href.startswith('http'):
            links.append(href)
    return links

# urls = extract_links('https://news.ycombinator.com')
# print(urls[:5])

妥善处理格式错误的 HTML

现实世界中的 HTML 经常存在问题:标签未闭合、元素不匹配或编码错误。BeautifulSoup 的解析器具有较强的容错能力,会尝试自动修复错误。不过,访问嵌套元素时,请始终防范 None。

from bs4 import BeautifulSoup

# Broken HTML — missing closing tags
html = '<div><p>Hello <strong>World</div>'
soup = BeautifulSoup(html, 'html.parser')

# BS4 repairs the tree automatically
print(soup.prettify())
# <div><p>Hello <strong>World</strong></p></div>

# Safe chained access
price = soup.find('span', class_='price')
price_text = price.text.strip() if price else 'N/A'
print(price_text)  # 'N/A'

智能体完整抓取工具

将这些内容整合起来:这是一个完整的抓取函数,智能体可以将其作为工具调用。它会获取页面、解析页面,并以智能体能够进行推理的格式返回结构化数据。

from bs4 import BeautifulSoup
import httpx

def scrape_article(url: str) -> dict:
    response = httpx.get(url, headers={'User-Agent': 'MyAgent/1.0'}, timeout=10.0)
    response.raise_for_status()
    soup = BeautifulSoup(response.text, 'html.parser')

    title = soup.find('h1')
    paragraphs = soup.find_all('p')

    return {
        'url': url,
        'title': title.text.strip() if title else '',
        'text': ' '.join(p.text.strip() for p in paragraphs[:5]),
        'links': [a.get('href') for a in soup.find_all('a', href=True)][:10]
    }

知识检查:BeautifulSoup

请测试您对使用 BeautifulSoup 解析 HTML 的理解。

回顾:使用 BeautifulSoup 解析 HTML

现在,您已经可以在智能体中从 HTML 页面提取结构化数据:

  • 使用 BeautifulSoup(html, 'html.parser') 创建解析对象
  • 使用 find() 查找单个元素,使用 find_all() 查找多个元素
  • 使用 select() 执行 CSS 选择器查询
  • 使用 .text.strip() 获取文本,使用 .get('attr') 获取属性
  • 使用 .parent、.children 和兄弟节点遍历树结构

结合 HTTP 客户端后,BeautifulSoup 让您的智能体能够读取任意网页。

常见问题解答

「使用 BeautifulSoup 解析 HTML」课时是免费的吗?

是的 — 「使用 BeautifulSoup 解析 HTML」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 AI Agents 课程的其余内容,请升级到 CoddyKit PRO。 AI Agents 课程共包含 4 节课。

「使用 BeautifulSoup 解析 HTML」这节课中我会学到什么?

find()、select()、CSS 选择器,以及从 HTML 中提取结构化内容。 你通过在浏览器中直接运行的动手代码来练习 AI Agents,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 AI Agents 需要有经验吗?

无需任何先前经验。CoddyKit 上的 AI Agents 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「使用 BeautifulSoup 解析 HTML」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 AI Agents 课中编写并运行代码吗?

能。每节 AI Agents 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 代理使用的 HTTP 客户端:httpx 与 requests
  2. 使用 BeautifulSoup 解析 HTML
  3. 处理分页与动态内容
  4. 遵守规范的抓取实践
← 返回 AI Agents