蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行本章核心实例

PYTHONOwned loopback and parser fixturespython-spider-beautifulsoup.py
python-spider-beautifulsoup.py228 行
"""蓝色天空网 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()
本例需在 Owned loopback and parser fixtures 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Owned loopback and parser fixtures

入口文件:projects/python-lab/python-spider-beautifulsoup.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 python-spider-beautifulsoup.py,或下载右侧课程工程包。
  2. 确认本地已准备 Owned loopback and parser fixtures。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Python

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

下载课程关联工程包:Python

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

下载课程关联工程包:Python

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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