蓝色天空.知识 · 实践 · 创造
我的收藏
Python 教程目录 82章
课程介绍
Python / LEARN BY DOING

Python Beautiful Soup:从响应字节到结构化记录

分开验证 HTTP、字符编码和解析树,按标签与文本筛选,并在自建网页上演练节点修改和导出。

学完这一章,你能够

  • 分开验证 HTTP、字符编码和解析树,按标签与文本筛选,并在自建网页上演练节点修改和导出。

把请求、解析和存储分开

采集流程通常先通过 HTTP 获取有权访问的内容,再解析、定位字段并保存到 CSV、JSON 或数据库。Requests 管请求,Beautiful Soup 管 HTML 或 XML 解析树,lxml 可以作为解析后端。Scrapy 是包含调度、下载和提取能力的框架。本站实验只访问自建回环站点。

在同一个虚拟环境用 python -m pip install beautifulsoup4 requests 安装包,通过 from bs4 import BeautifulSoup 导入。html.parser 是 Python 自带的 HTML 解析器。若用 lxml、XML 模式或 html5lib,要分别准备支持该模式的解析器。遇到不规范 HTML,不同解析器可能生成不同的树,因此需要显式指定后端。

请求应设置超时,并在解析之前检查响应状态。先用 raise_for_status() 处理失败响应,再将 response.content 字节交给解析器,或按核定的编码取 response.text。title 不一定存在,先判断结果再取文字。

保留字节并核对中文解码

response.content 保留响应体字节,response.text 按当前 response.encoding 解码。响应头中的 charset 可以缺失或写错。实验返回一份 GBK 页面,故意给它错误的 UTF-8 声明,核对乱码后再明确设为 gbk,或者给 BeautifulSoup 的字节输入传 from_encoding="gbk"。

未知编码时可把候选探测结果与响应头、HTML 声明和字符样本交叉核对。旧例使用可选的 chardet,本站环境用 Beautiful Soup 的 UnicodeDammit 检测带 UTF-8 声明的受控样本,并检查解码结果。短文本或编码接近时,探测结果可能无法区分多种编码。

区分标签、属性和文本

find() 返回第一个匹配项或 None。find_all() 返回全部匹配项,空结果可直接迭代。get("href") 允许属性缺失时返回默认值,而 tag["href"] 缺键会抛 KeyError。本文用搜索表单的实际 id 查找输入元素,并读它的 value。

用 class_、id 或 attrs 限定属性,CSS 查询可用 select("a[href]") 等选择器。find_all(string=...) 单独使用时返回文本节点,和标签名一起用时筛标签的 .string。它与按类名查找是不同操作。

.get_text(" ", strip=True) 合并后代文本,可指定分隔符。一个标签有多个内容节点时,.string 可能是 None。唯一子链最终只有一段字符串时,.string 可沿子链取得它。

按树关系移动并修改节点

parent 是直接父节点,children 与 contents 对应直接子节点,descendants 会遍历后代,直接子节点和后代都可以包含文本。next_sibling 和 previous_sibling 会遇到空白或普通文字,带筛选条件的 find_next_sibling 等方法可按标签查找。next_element 和 previous_element 按解析顺序移动,也会遇到文本。

find_all_next 与 find_all_previous 沿解析顺序向后和向前筛选。要判定祖先关系,用 any(node is ancestor for node in tag.parents) 检查节点身份。Beautiful Soup 4.15.0 没有可调用的 is_ancestor_of 或 is_descendant_of,结构相同的两个节点也可能不是同一节点。

extract() 拆下节点并返回它,unwrap() 去掉外壳并保留孩子,decompose() 删除节点和后代。clear() 清空内容但保留当前标签。replace_with() 返回被替换的旧节点,insert()、insert_before()、insert_after() 可放置节点或文本。

输出文本、结构化记录或 HTML

str(soup) 生成序列化后的 HTML,prettify() 为阅读添加缩进和换行,encode() 输出字节。序列化可能调整标签和空白,要保留原始 HTML 字节应单独存档。XML 模式区分大小写,不能当作普通 HTML 树处理。

下面的本站结果页显示实验从本机页面提取出的标题和带地址链接。脚本把同一组记录写到 JSON 和 CSV。下载 ZIP 后在所需 Python 环境执行 python python-spider-beautifulsoup.py --output output,可重做请求、解析、修改及落盘检查。

本站结果页列出入门和札记两个提取项及其路径
本站实验从自建页面提取出的真实记录。缺少 href 的链接被排除。

尝试一下 ↗ 在独立页面修改并运行

下载本章实验包 (mbskycom202611a463.zip) ↓ 查看运行说明 ↗

解析树搜索与操作

调用或属性结果与条件
BeautifulSoup(markup, features=...)指定 HTML 或 XML 后端,返回解析树。
prettify()输出便于阅读的缩进字符串。
find(name, ...)返回第一个匹配项,缺失返回 None。
find_all(name, ...)返回匹配集合,找不到返回空集合。
find_all_next(name)在后续解析顺序中筛选节点,包含后续后代。
find_all_previous(name)按反向解析顺序筛选先前节点。
find_parent(name)沿祖先链返回首个匹配标签。
find_parents(name)收集符合条件的祖先。当前方法名是 find_parents。
find_next_sibling(name)从同层向后找首个匹配项。
find_previous_sibling(name)从同层向前找首个匹配项。
parent返回直接父节点。
next_sibling返回紧邻的同层节点,可能是文本。
previous_sibling返回前一个同层节点,可能是文本。
get_text(separator, strip=...)将后代文本拼接成字符串,可选分隔符和去边缘空白。
attrs返回属性映射,HTML 多值属性可能是列表。
string唯一字符串路径可取值,混合内容可能返回 None。
name标签名称。
contents / children直接子节点的列表或迭代器,可含文本。
descendants遍历所有后代标签和文本。
parent返回直接父节点。
previous_element解析顺序中前一个节点,可能是文本。
next_element解析顺序中后一个节点,可能是文本。
decompose()从树移除标签及后代并销毁其内容。
unwrap()移除标签外壳,让孩子留在原树。
insert(index, child)按索引插入直接子节点。
insert_before(item)在当前节点之前插入同层内容。
insert_after(item)在当前节点之后插入同层内容。
extract()拆下节点并返回可继续使用的节点。
replace_with(item)用新节点替换旧节点,返回旧节点。
has_attr(name)判断当前标签是否含有该属性。
get(name, default=None)按属性名获取值,缺失时返回指定默认值。
clear()移除当前标签的内容,保留标签。
encode(encoding)将序列化后的 HTML 变成字节。
is_empty_element由解析器判断标签是否能以空元素形式呈现,区别于普通空标签。
any(node is ancestor for node in tag.parents)用身份比较验证祖先,当前 Tag 无该方法。
any(node is ancestor for node in tag.parents)以待测后代的 parents 迭代验证归属,当前 Tag 无该方法。

属性与访问方式

调用或属性结果与条件
tag.get("style")读取内联样式属性。tag.style 会尝试按名称找子标签。
tag.get("id")读取 HTML 的 id 属性。
tag.get("class")读取 class 的多值列表。class_ 用作搜索参数。
string唯一字符串路径可取值,混合内容可能返回 None。
parent返回直接父节点。

find_all 筛选参数

调用或属性结果与条件
find_all(string=...)筛选文本节点,带标签名时筛选标签的 string。
find_all(id=...)筛选指定 id 属性的标签。
find_all(attrs={...})按属性名和值筛选匹配标签。

本章自编源码与运行范围

含完整源码 · 228 行
展开查看收起
Python
"""蓝色天空网 mbsky.com · 自建回环页面的解析和导出实验。"""
import argparse
from contextlib import contextmanager
import csv
from html import escape
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
from pathlib import Path
import platform
import sys
from threading import Thread

import bs4
from bs4 import BeautifulSoup, NavigableString, UnicodeDammit
import lxml
import requests

sys.path.insert(0, str(Path(__file__).resolve().parent))
from mbsky_pychecks import Checks

DOC = """<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><title>蓝天资料架</title></head>
<body><p id="before">索引说明</p><main id="rack" class="panel featured" style="color: navy">
<p id="intro">去 <b>蓝天</b> 找资料</p><section id="shelf"><a href="/guide">入门</a> · <a href="/notes">札记</a><a>无地址</a>
<div class="nested"><div class="nested">内层</div></div></section>
<input id="local-query" value="检索资料"><p id="after">目录尾注</p></main><footer>蓝色天空网</footer></body></html>"""


@contextmanager
def local_site():
    class Handler(BaseHTTPRequestHandler):
        def log_message(self, *_):
            pass

        def do_GET(self):
            status, raw, charset = {
                "/": (200, DOC.encode("utf8"), "utf-8"),
                "/gbk": (200, "<title>北岸资料</title>".encode("gbk"), "utf-8"),
                "/no-title": (200, b"<p>No title</p>", "utf-8"),
            }.get(self.path, (404, b"Not found", "utf-8"))
            self.send_response(status)
            self.send_header("Content-Type", "text/html; charset=" + charset)
            self.send_header("Content-Length", str(len(raw)))
            self.end_headers()
            self.wfile.write(raw)

    with ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server:
        worker = Thread(target=server.serve_forever, daemon=True)
        worker.start()
        try:
            yield f"http://127.0.0.1:{server.server_port}"
        finally:
            server.shutdown()
            worker.join(timeout=3)


def fetch(check):
    with local_site() as base, requests.Session() as client:
        client.trust_env = False
        response = client.get(base + "/", timeout=3, allow_redirects=False)
        response.raise_for_status()
        check.eq("real HTTP bytes and status", (response.status_code, response.content), (200, DOC.encode("utf8")))
        check.eq("UTF-8 declared by server", response.encoding.lower(), "utf-8")
        check.eq("header decoder returns UTF-8 text", response.text, DOC)
        soup = BeautifulSoup(response.content, "html.parser")
        check.eq("html parser produces title", soup.title.get_text(), "蓝天资料架")
        check.eq("lxml parser produces title", BeautifulSoup(response.content, "lxml").title.get_text(), "蓝天资料架")

        legacy = client.get(base + "/gbk", timeout=3, allow_redirects=False)
        legacy.raise_for_status()
        check.eq("mislabeled encoding produces wrong text", "北岸资料" in legacy.text, False)
        legacy.encoding = "gbk"
        check.eq("explicit Requests GBK", legacy.text, "<title>北岸资料</title>")
        legacy_tree = BeautifulSoup(legacy.content, "html.parser", from_encoding="gbk")
        check.eq("explicit Beautiful Soup GBK", legacy_tree.title.get_text(), "北岸资料")
        decoded = UnicodeDammit(response.content, is_html=True)
        check.eq("detected UTF-8 declared in the markup", (decoded.original_encoding, decoded.unicode_markup), ("utf-8", DOC))

        no_title = client.get(base + "/no-title", timeout=3, allow_redirects=False)
        no_title.raise_for_status()
        check.eq("missing title is None", BeautifulSoup(no_title.content, "html.parser").find("title"), None)
        missing = client.get(base + "/missing", timeout=3, allow_redirects=False)
        check.eq("HTTP missing returns 404", missing.status_code, 404)
        check.raises("raise for HTTP failure before parsing", requests.HTTPError, missing.raise_for_status)
        return soup


def search(check, soup):
    main, intro, shelf = soup.main, soup.find(id="intro"), soup.find(id="shelf")
    first = shelf.find("a")
    check.eq("first match and missing tag", (first.get_text(), shelf.find("button")), ("入门", None))
    check.eq("all links and no matches", ([a.get_text() for a in shelf.find_all("a")], len(shelf.find_all("button"))),
             (["入门", "札记", "无地址"], 0))
    check.eq("has_attr checks attribute", (first.has_attr("href"), shelf.find_all("a")[-1].has_attr("href")), (True,False))
    no_href = shelf.find_all("a")[-1]
    check.eq("get and indexing differ on absent attribute", no_href.get("href", "/fallback"), "/fallback")
    check.raises("attribute index raises on absent key", KeyError, lambda: no_href["href"])
    check.eq("attribute mapping returns class list", dict(main.attrs, **{"class": list(main["class"])}),
             {"id":"rack","class":["panel","featured"],"style":"color: navy"})
    check.eq("style attribute differs from child lookup", (main.get("style"), main.style), ("color: navy", None))
    check.eq("id attribute access", (main.get("id"), main.id), ("rack", None))
    check.eq("tag name", first.name, "a")
    check.eq("combined descendant text", intro.get_text(" ",strip=True), "去 蓝天 找资料")
    check.eq("string requires a single chain", (intro.string, str(intro.b.string)), (None, "蓝天"))
    check.eq("string selector returns text nodes",
             ([type(x).__name__ for x in soup.find_all(string="入门")],
              [x.name for x in soup.find_all("a", string="入门")]), (["NavigableString"],["a"]))
    check.eq("find_all id attribute", [x.name for x in soup.find_all(id="rack")], ["main"])
    check.eq("find_all attrs filter", [x.get_text() for x in soup.find_all(attrs={"href":"/guide"})], ["入门"])
    check.eq("CSS attribute selector", [a["href"] for a in shelf.select("a[href]")], ["/guide","/notes"])
    check.eq("class and nested selection", (len(main.find_all("div",class_="nested")),
             len(main.select("div.nested div.nested"))), (2,1))
    check.eq("find button by actual id", soup.find("input", id="local-query")["value"], "检索资料")


def traversal(check, soup):
    shelf = soup.find(id="shelf")
    first, second, _ = shelf.find_all("a")
    intro = soup.find(id="intro")
    check.eq("search forward in parse order", [p["id"] for p in intro.find_all_next("p")], ["after"])
    check.eq("search backward in parse order", [p["id"] for p in shelf.find_all_previous("p")], ["intro","before"])
    check.eq("filtered nearest parent", first.find_parent("main")["id"], "rack")
    check.eq("filtered parent list", [p.name for p in first.find_parents(["main","section"])], ["section","main"])
    check.eq("nonexistent all-parent alias", callable(first.find_all_parents), False)
    check.eq("filtered next sibling skips text", first.find_next_sibling("a") is second, True)
    check.eq("filtered previous sibling skips text", second.find_previous_sibling("a") is first, True)
    check.eq("direct parent", first.parent is shelf, True)
    check.eq("next sibling can be text", (isinstance(first.next_sibling,NavigableString),str(first.next_sibling)), (True," · "))
    check.eq("previous sibling can be text", str(second.previous_sibling), " · ")
    check.eq("previous element can be text", str(second.previous_element), " · ")
    check.eq("next element can be text", str(first.next_element), "入门")
    check.eq("contents and children include text",
             (list(intro.children)==intro.contents,[type(x).__name__ for x in intro.contents]),
             (True,["NavigableString","Tag","NavigableString"]))
    check.eq("descendants include nested text", [type(x).__name__ for x in intro.descendants],
             ["NavigableString","Tag","NavigableString","NavigableString"])
    twins = BeautifulSoup("<div><b>同样</b></div><div><b>同样</b></div>","html.parser").find_all("div")
    child=twins[1].b
    check.eq("ancestry needs identity", (twins[0]==twins[1], any(p is twins[0] for p in child.parents),
             any(p is twins[1] for p in child.parents)), (True,False,True))
    check.eq("historical ancestry names are not callable", (callable(twins[0].is_ancestor_of),
             callable(child.is_descendant_of)), (False,False))


def edit_tree(check):
    soup = BeautifulSoup("<main><p>甲</p><div><i>乙</i></div><b>丙</b><span>丁</span><br><div></div></main>","html.parser")
    first=soup.p
    first["class"]=["edited"]
    first.string="新甲"
    check.eq("change text and attribute", (first.get_text(),list(first["class"])), ("新甲",["edited"]))
    first.insert(0,"前缀")
    check.eq("insert adds child at index", str(first.contents[0]), "前缀")
    first.insert_before("起")
    check.eq("insert_before creates sibling",str(first.previous_sibling),"起")
    first.insert_after("承")
    check.eq("insert_after creates sibling",str(first.next_sibling),"承")
    detached=soup.b.extract()
    check.eq("extract returns reusable detached tag", (detached.parent,detached.get_text(),soup.b), (None,"丙",None))
    old=soup.span.replace_with(detached)
    check.eq("replace_with returns old tag", (old.name,old.parent,soup.b.get_text()), ("span",None,"丙"))
    wrapper=soup.div
    wrapper.unwrap()
    check.eq("unwrap keeps child content", (wrapper.parent,soup.i.get_text(),soup.i.parent.name), (None,"乙","main"))
    soup.i.decompose()
    check.eq("decompose removes subtree", soup.i, None)
    first.clear()
    check.eq("clear preserves tag", (first.parent.name,first.get_text(),list(first["class"])), ("main","",["edited"]))
    check.eq("void elements versus empty containers", (soup.br.is_empty_element,soup.div.is_empty_element), (True,False))
    check.eq("pretty output adds line breaks", "\n" in soup.prettify(), True)
    check.eq("encode returns UTF-8 bytes", soup.b.encode("utf-8"), "<b>丙</b>".encode("utf8"))
    check.eq("str output preserves modified tree",
             BeautifulSoup(str(soup),"html.parser").b.get_text(),"丙")


def parser_variants(check):
    invalid="<a></p>"
    check.eq("malformed HTML depends on parser",
             [(tree.html is not None,tree.find("p") is not None) for tree in
              (BeautifulSoup(invalid,p) for p in ("html.parser","lxml","html5lib"))],
             [(False,False),(True,False),(True,True)])
    xml=BeautifulSoup("<Shelf><Entry Key='A'/></Shelf>","xml")
    check.eq("XML case-sensitive tag and attribute", (xml.find("entry"),xml.Entry["Key"]), (None,"A"))


def export(check, soup, target):
    target.mkdir(parents=True,exist_ok=True)
    rows=[{"label":a.get_text(strip=True),"path":a["href"]} for a in soup.select("#shelf a[href]")]
    text=json.dumps(rows,ensure_ascii=False,indent=2)+"\n"
    (target/"links.json").write_text(text,encoding="utf8")
    with (target/"links.csv").open("w",encoding="utf8",newline="") as file:
        writer=csv.DictWriter(file,fieldnames=["label","path"])
        writer.writeheader()
        writer.writerows(rows)
    expected=[{"label":"入门","path":"/guide"},{"label":"札记","path":"/notes"}]
    check.eq("JSON export round-trips",json.loads((target/"links.json").read_bytes()),expected)
    with (target/"links.csv").open(encoding="utf8",newline="") as file:
        check.eq("CSV export round-trips",list(csv.DictReader(file)),expected)
    body="".join(f"<tr><td>{escape(r['label'])}</td><td><code>{escape(r['path'])}</code></td></tr>" for r in rows)
    report=('<!doctype html><html lang="zh-CN"><meta charset="utf-8"><title>本站解析结果</title>'
            '<style>body{background:#ebf4ff;color:#183c62;font:22px system-ui;padding:45px;}'
            'main{max-width:700px;margin:auto;padding:26px;background:#fff;border-radius:16px}'
            'th,td{padding:8px 18px;text-align:left}small{color:#37658e}</style><main>'
            f'<small>蓝色天空网 · Beautiful Soup 本机实验</small><h1>{escape(soup.title.get_text())}</h1>'
            f'<p>从自建页面提取 {len(rows)} 条有地址链接</p><table><tr><th>名称</th><th>路径</th></tr>'
            f'{body}</table></main></html>')
    (target/"report.html").write_bytes(report.encode("utf8"))
    check.eq("HTML report serializes exact record rows",
             [[td.get_text() for td in tr.find_all("td")] for tr in
              BeautifulSoup(report,"html.parser").select("tr")[1:]], [["入门","/guide"],["札记","/notes"]])


def main():
    parser=argparse.ArgumentParser()
    parser.add_argument("--output",type=Path,default=Path("beautifulsoup-output"))
    args=parser.parse_args()
    check=Checks()
    soup=fetch(check)
    search(check,soup)
    traversal(check,soup)
    edit_tree(check)
    parser_variants(check)
    export(check,soup,args.output)
    check.finish("python-spider-beautifulsoup",python=platform.python_version(),beautifulsoup=bs4.__version__,
                 requests=requests.__version__,lxml=lxml.__version__,scope="Owned loopback and parser fixtures")


if __name__=="__main__":
    main()

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

当前源码有命名范围的实际运行记录;原文全部事实、其它平台和IDE界面仍待逐项验收。

本章附件与实例包

下载课程关联工程包:Python

课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202611a463.zip

下载课程关联工程包:Python

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202611a464.zip

下载课程关联工程包:Python

课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202612a292.zip

常见错误与边界检查

  • 命令、源码、当前解释器和具体平台分别核对,不能以单项运行推断整章验收。

技术规范与官方资料

练习与参考解答

查看参考解答

比较原始输出、修改后的输出及错误类型;未执行的平台和界面继续单列。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习