爬虫-BeautifulSoup

这篇讲什么

  • BeautifulSoup 4.15 的用法按「查找 → 取属性 → 取文本 → 遍历 → 改结构」五步走,每条都带本机实测输出。
  • 抓页面的示例都指向公开练习站 scrape.center,它是《Python3 网络爬虫开发实战》的作者搭的,专门给爬虫练手,不校验请求头。
  • 解析器不是随便选:html.parser、lxml、html5lib 对同一份残缺 HTML 的补全结果不一样,真实列表页上的速度实测差近 3 倍。
  • 记下三个真实踩坑点:不指定解析器会吃 GuessedAtParserWarning、find_all(text=) 已弃用、往文档里塞「用 lxml 解析出来的片段」会连 <html><body> 一起搬进去。

安装与解析器

  • bs4 本体 + 至少一个解析器,实测本机版本:

    1
    pip install beautifulsoup4 lxml html5lib
    1
    2
    3
    4
    beautifulsoup4 4.15.0
    lxml 6.1.3
    html5lib 1.1
    soupsieve 4.0.1 # CSS 选择器是它实现的
  • 不指定解析器会怎样,实测第一条就报警告:

    default_parser.py
    1
    2
    3
    4
    from bs4 import BeautifulSoup

    soup = BeautifulSoup("<a><b>x</b></a>")
    print(str(soup))
    1
    2
    3
    GuessedAtParserWarning: No parser was explicitly specified, so I'm using the best available
    HTML parser for this system ("lxml"). ... pass the additional argument 'features="lxml"'
    <html><body><a><b>x</b></a></body></html>
    • 它「猜」的是本机最好的那个,换台机器结果就变(连输出结构都会变,因为 lxml 会补 <html><body>)。永远显式写解析器名。
  • 名字写错或没装就抛异常,实测:

    bad_parser.py
    1
    2
    3
    4
    5
    6
    from bs4 import BeautifulSoup

    try:
    BeautifulSoup("<a>x</a>", "no-such-parser")
    except Exception as e:
    print(f"{type(e).__module__}.{type(e).__name__}: {e}")
    1
    bs4.exceptions.FeatureNotFound: Couldn't find a tree builder with the features you requested: no-such-parser. Do you need to install a parser library?
  • 三个解析器对同一份残缺 HTML 的处理,实测:

    parsers.py
    1
    2
    3
    4
    5
    from bs4 import BeautifulSoup

    bad = "<div><p>没闭合<b>粗体</div>"
    for name in ["html.parser", "lxml", "html5lib"]:
    print("%-11s %s" % (name, str(BeautifulSoup(bad, name))))
    1
    2
    3
    html.parser <div><p>没闭合<b>粗体</b></p></div>
    lxml <html><body><div><p>没闭合<b>粗体</b></p></div></body></html>
    html5lib <html><head></head><body><div><p>没闭合<b>粗体</b></p></div></body></html>
    • 差别有两层:lxml/html5lib 会补全 html/body(甚至 head),html.parser 原样保留;三者都帮你闭合了 <b>。
    • 所以 soup.div 这种写法在 lxml 下能直接找到,而 soup.html.div 在 html.parser 下会找不到——换解析器时这类「路径变了」的 bug 很常见。
  • 速度实测:抓 ssr1 的 10 个列表页(/page/1 到 /page/10)拼成一份真实 HTML(415715 个字符),再整份重复一次凑到 812 KB,单轮耗时够长,毫秒级的抖动才不至于让数字跳档。每个解析器连跑 24 轮,去掉最快、最慢各两轮取平均(顺手关掉循环 GC)。第二列是同一份数据上「解析 + 用 CSS 取 200 个评分」的耗时。

    parser_speed.py
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    import gc
    import time
    import urllib.request

    from bs4 import BeautifulSoup

    HEADERS = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/156.0"}
    pages = []
    for page in range(1, 11):
    req = urllib.request.Request("https://ssr1.scrape.center/page/%d" % page, headers=HEADERS)
    pages.append(urllib.request.urlopen(req, timeout=30).read().decode())
    HTML = "".join(pages) * 2 # 整份重复一次:单轮耗时够长,毫秒级抖动不至于跳档
    ROUNDS = 24


    def round_time(parser, with_css):
    """连跑 ROUNDS 轮,去掉最快、最慢各两轮取平均;关循环 GC 让每轮可比。"""
    gc.disable()
    try:
    rounds = []
    for _ in range(ROUNDS):
    t0 = time.perf_counter()
    soup = BeautifulSoup(HTML, parser)
    if with_css:
    len(soup.select("p[class*='score']")[:200])
    rounds.append(time.perf_counter() - t0)
    finally:
    gc.enable()
    rounds.sort()
    mid = rounds[2:-2]
    return sum(mid) / len(mid)


    print("%d 个列表页拼一份再重复一次:%d 个字符(%.0f KB)" % (len(pages), len(HTML), len(HTML) / 1024))
    print("%-12s %8s %s" % ("解析器", "只解析", "解析 + 取值"))
    for parser in ("lxml", "html.parser", "html5lib"):
    print("%-12s %6.2fs %6.2fs" % (parser, round_time(parser, False), round_time(parser, True)))
    1
    2
    3
    4
    5
    10 个列表页拼一份再重复一次:831430 个字符(812 KB)
    解析器 只解析 解析 + 取值
    lxml 0.17s 0.19s
    html.parser 0.26s 0.28s
    html5lib 0.49s 0.50s
    解析器 速度 容错 什么时候用
    lxml 最快 强 默认选择,需要额外装 C 扩展
    html.parser 中等 一般 不想装第三方库、或要求「不补 html/body」
    html5lib 最慢 最强 页面烂到 lxml 都排不对时,它按浏览器的解析规则来
    • 差距比传闻里小得多:这份 812 KB 上 lxml 只比 html.parser 快 0.09 秒,html5lib 也只有 lxml 的 2.9 倍。
  • 解析 XML(RSS、接口返回的 XML)要用 XML 系解析器,实测 lxml-xml 与 xml 都可用,并且会自动加 XML 声明:

    xml_parser.py
    1
    2
    3
    4
    from bs4 import BeautifulSoup

    for name in ("lxml-xml", "xml"):
    print("%s -> %s" % (name, BeautifulSoup("<a><b>x</b></a>", name)))
    1
    2
    3
    4
    lxml-xml -> <?xml version="1.0" encoding="utf-8"?>
    <a><b>x</b></a>
    xml -> <?xml version="1.0" encoding="utf-8"?>
    <a><b>x</b></a>

四种查找方式

  • 拿 ssr1 列表页第 2 页 https://ssr1.scrape.center/page/2 做实验,一张卡片是 <div class="el-card item m-t is-hover-shadow"> 里套 <a href="/detail/11" class="name"><h2>V字仇杀队 - V for Vendetta</h2></a> 与 <p class="score m-t-md m-b-n-sm">8.9</p>:

    find.py
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    import re
    import urllib.request

    from bs4 import BeautifulSoup

    html = urllib.request.urlopen("https://ssr1.scrape.center/page/2", timeout=20).read().decode()
    soup = BeautifulSoup(html, "lxml")

    print(soup.find("a").get("href"), "|", soup.find("a").get_text(strip=True))
    print(len(soup.find_all("a")), len(soup.find_all("a", limit=2)))
    print(len(soup.find_all(["a", "h2"])))
    print([t.get_text(strip=True) for t in soup.find_all(class_="score")][:3])
    print(soup.find_all("a", attrs={"class": "name"})[0].h2.string)
    print(soup.find(id="index").name)
    print(len(soup.find_all(string=re.compile(r"^\s*8\.\d\s*$"))))
    print([h.get_text(strip=True) for h in soup.select("div.el-card.item a.name h2")][:3])
    print(len(soup.select('a[href^="/detail"]')))
    print(soup.select_one("span.el-pagination__total"))
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    / | Scrape
    34 2
    44
    ['8.9', '8.9', '8.8']
    V字仇杀队 - V for Vendetta
    div
    6
    ['V字仇杀队 - V for Vendetta', '少年派的奇幻漂流 - Life of Pi', '美丽心灵 - A Beautiful Mind']
    20
    <span class="el-pagination__total">共 104 条</span>
  • 对应关系:find / find_all 是 bs4 自己的接口,select / select_one 走 CSS 选择器(由 soupsieve 实现)。同一个需求两种都能做,select 写复杂层级更短,find_all 传函数和正则更灵活。

  • a.name 里面既有换行文本又有 h2,.string 实测拿到 None,取片名要写 .h2.string 或 .get_text(strip=True)。

  • a[href^="/detail"] 实测 20 条 = 10 张卡片 × 2,封面图和片名各套了一个 a,只数 a 会把链接数翻倍。

  • find_all 的常用参数(全部实测):

    • 位置参数:标签名,可以是字符串、列表 ["a", "span"]、正则 re.compile(r"^s")、函数,或 True。
    • attrs={...}:按属性字典查;class_="score" 是 attrs={"class": "score"} 的简写(注意是尾下划线,class 是 Python 关键字)。
    • id="index":等价 attrs={"id": ...}。
    • string=:按文本内容查,能传字符串、正则、函数。
    • limit=2:只要前两个。
    • recursive=False:只看直接子节点,实测 <a><b><c>x</c></b></a> 里 find_all("c", recursive=False) 返回 0 条。
  • ⚠️ find_all(text="下一页") 还能用,但实测会抛 DeprecationWarning;新代码一律写 string=,两者结果相同(都返回 1 条)。

  • soup.a 这种属性写法只能拿到第一个同名标签,实测 str(soup.a) == str(soup.find("a")) 为 True。它好看但不安全,标签一多就建议写全 find。

取属性

attrs.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import urllib.request

from bs4 import BeautifulSoup

html = urllib.request.urlopen("https://ssr1.scrape.center/page/2", timeout=20).read().decode()
soup = BeautifulSoup(html, "lxml")
a = soup.select_one("a.name")

print(a["class"])
print(a["href"], "|", a.get("nope", "默认"))
print(a.attrs)
print("href" in a.attrs, "nope" in a.attrs)
print(soup.select('div.el-card.item a[href^="/detail"]')[0].get("class"))

img = BeautifulSoup('<img src="x" alt="y">', "lxml").img
del img["alt"]
print(str(img))
1
2
3
4
5
6
['name']
/detail/11 | 默认
{'data-v-7f856186': '', 'href': '/detail/11', 'class': ['name']}
True False
[]
<img src="x"/>
  • class 永远是列表,因为 HTML 允许多个类名。所以 a["class"] == "name" 是 False,要写 "name" in a["class"],封面那个 <a class=""> 实测取出的是空列表 []。
  • a["href"] 缺键会 KeyError,a.get("href") 返回 None;属性存在性判断用 "href" in a.attrs(对 a 直接用 in 是按子节点找,语义不同)。
  • attrs 是那个字典本体,改它等于改标签;del tag["alt"] 实测直接生效。

取文本

  • 详情页 https://ssr1.scrape.center/detail/11 的两行基本信息长这样:<div class="m-v-sm info"><span>美国、英国、德国</span><span> / </span><span>132 分钟</span></div>,实测四种取法:

    text.py
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    import urllib.request

    from bs4 import BeautifulSoup, Comment, NavigableString

    html = urllib.request.urlopen("https://ssr1.scrape.center/detail/11", timeout=20).read().decode()
    soup = BeautifulSoup(html, "lxml")

    print(repr(soup.find("div", class_="info").get_text(strip=True)))
    print(repr(soup.find("div", class_="info").get_text("|", strip=True)))
    print(list(soup.find("div", class_="categories").strings))
    print(list(soup.select_one(".director").stripped_strings))
    print(soup.find("h2").text)
    print([str(x)[:18] for x in soup.find_all(string=lambda t: isinstance(t, Comment))][:4])
    print(sum(1 for x in soup.select_one("p[class*=score]").descendants if isinstance(x, NavigableString)))
    print(BeautifulSoup("<p>&amp;x</p>", "lxml").p.decode_contents())
    print(BeautifulSoup(b"<p>\xc3\xa9</p>", "lxml").p.string)
    1
    2
    3
    4
    5
    6
    7
    8
    9
    '美国、英国、德国/132 分钟'
    '美国、英国、德国|/|132 分钟'
    ['\n', '\n', '剧情', '\n', '\n', '\n', '动作', '\n', '\n', '\n', '科幻', '\n', '\n', '\n', '惊悚', '\n', '\n']
    ['詹姆斯·麦克特格']
    V字仇杀队 - V for Vendetta
    [' ', ' ', ' ', ' ']
    1
    &amp;x
    é
  • 该用哪个:

    • get_text() 把整棵子树的文字拼成一个字符串,strip=True 去掉每段首尾空白。
    • 第一个参数是连接符,实测 "|" 拼出 美国、英国、德国|/|132 分钟,不写连接符就粘成 美国、英国、德国/132 分钟。
    • strings / stripped_strings 是逐段迭代,想按行取字段就用它;strings 会把换行缩进当独立元素,stripped_strings 直接跳过空白。
    • tag.text 等价 get_text()。
    • decode_contents() 保留内部标签(实测 &amp;x 原样留着),要拿 HTML 片段就用它或 str(tag)。
  • 传 bytes 进去 bs4 会自己猜编码,实测 b"<p>\xc3\xa9</p>" 得到 é。猜错时显式给 from_encoding="utf-8"。

  • 注释也是节点,用 isinstance(t, Comment) 过滤才取到。ssr1 详情页的注释全是 Vue 条件渲染留下的空壳,实测 261 个里非空的 0 个,打出来清一色 ' '。

遍历文档树

walk.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import urllib.request

from bs4 import BeautifulSoup

html = urllib.request.urlopen("https://ssr1.scrape.center/page/2", timeout=20).read().decode()
soup = BeautifulSoup(html, "lxml")
card = soup.select_one("div.el-card.item")
title = card.h2

print([p.name for p in title.parents][:5])
print(len(list(card.children)), len(list(card.descendants)), len(card.contents))
print(repr(str(card.next_sibling)[:1]), repr(str(card.previous_sibling)[:1]))
print([str(x)[:12] for x in card.next_siblings][:3])
print(card.find_parent("div", id="index").get("id"), "|", card.find_parents("a"))
print(len(card.find_all_next("span")), "|", len(card.find_all("span")))
1
2
3
4
5
6
['a', 'div', 'div', 'div', 'div']
3 101 3
'\n' '\n'
['\n', '<div class="', '\n']
index | []
119 | 13
  • children / descendants / strings / parents 都是生成器,contents 是列表。生成器只能走一遍,要重复用就 list()。
  • 兄弟节点里混着换行文本,实测 next_sibling 就是 '\n'。想跳过空白用 find_next_sibling()(不带参数会跳文本节点)。
  • find_all_next 会从自己一路扫到文档末尾,实测第一张卡片往外数到 119 个 span,card.find_all("span") 只有 13 个,两者范围不同。
  • ⚠️ tag.siblings 与 tag.ancestors 在实测的 bs4 4.15 里取到的是 None(dir(Tag) 里根本没有这两个名字,而 Tag 对未知属性统一返回 None,所以不报错)。list(None) 直接 TypeError: 'NoneType' object is not iterable。要遍历兄弟用 next_siblings / previous_siblings,要遍历祖先用 parents。
  • 这个「未知属性返回 None」的行为本身是个坑:tag.zzz 实测也是 None。所以判断一个 API 存不存在,别看它有没有报错,要看 dir(tag)。

修改文档结构

  • 八个方法实测,每个都打印改完的整串:

    modify.py
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    from bs4 import BeautifulSoup

    s = BeautifulSoup("<div id='r'><p>旧</p><span>keep</span></div>", "html.parser")
    s.find("p").replace_with(BeautifulSoup("<h2>新</h2>", "html.parser"))
    print("replace_with:", s.div)

    s = BeautifulSoup("<div><b><i>x</i></b></div>", "html.parser")
    s.find("i").unwrap()
    print("unwrap:", s.div)

    s = BeautifulSoup("<div><b>drop</b><i>keep</i></div>", "html.parser")
    s.find("b").decompose()
    print("decompose:", s.div)

    s = BeautifulSoup("<p>a b</p>", "html.parser")
    s.find("p").clear()
    print("clear:", s.p)

    s = BeautifulSoup("<p>b</p>", "html.parser")
    s.find("p").insert(0, "A")
    print("insert:", s.p)

    s = BeautifulSoup("<p>a</p>", "html.parser")
    s.find("p").append("z")
    print("append:", s.p)

    s = BeautifulSoup("<div><p>x</p></div>", "html.parser")
    gone = s.find("p").extract()
    print("extract:", s.div, "| 取出:", gone)

    s = BeautifulSoup("<p>x</p>", "html.parser")
    s.find("p").wrap(s.new_tag("div"))
    print("wrap:", s)
    1
    2
    3
    4
    5
    6
    7
    8
    replace_with: <div id="r"><h2>新</h2><span>keep</span></div>
    unwrap: <div><b>x</b></div>
    decompose: <div><i>keep</i></div>
    clear: <p></p>
    insert: <p>Ab</p>
    append: <p>az</p>
    extract: <div></div> | 取出: <p>x</p>
    wrap: <div><p>x</p></div>
    方法 效果 和近邻的区别
    replace_with(新) 整段替换 被替换的节点离开文档
    unwrap() 去掉自己、保留子节点 与 decompose 相反
    decompose() 连子节点一起销毁 返回值没有意义
    clear() 清空子节点,标签留下
    insert(i, x) / append(x) 在指定位置 / 末尾插入 插入字符串会先转成 NavigableString
    extract() 摘下来并返回被摘的节点 想「移动节点」就 extract + append
    wrap(标签) 用给定标签把自己包一层 参数必须是 Tag,不能是 BeautifulSoup 对象,见下面那条
  • ⚠️ 构造「新片段」时也要指定解析器,而且用 lxml 会把 <html><body> 一起带进来。实测同样一行代码换解析器的后果:

    lxml_fragment.py
    1
    2
    3
    4
    5
    6
    from bs4 import BeautifulSoup

    s = BeautifulSoup("<div id='r'><p>旧</p><span>keep</span></div>", "html.parser")
    print('BeautifulSoup("<h2>新</h2>", "lxml") 放进文档 ->')
    s.find("p").replace_with(BeautifulSoup("<h2>新</h2>", "lxml"))
    print(s.div)
    1
    2
    BeautifulSoup("<h2>新</h2>", "lxml")  放进文档 ->
    <div id="r"><html><body><h2>新</h2></body></html><span>keep</span></div>
    • 同理 wrap(BeautifulSoup("<div class='w'></div>", "lxml")) 实测把整棵树包成了 <html><body><html><body>...。
    • wrap 还有第二种错法:参数要传标签,传整个 BeautifulSoup 对象实测会把自己塞进一个游离在小文档里的 div,结果 str(s) 只剩 <div class="w"></div>、s.p 变成 None。正确写法是 s.find("p").wrap(s.new_tag("div"))(实测得到 <div><p>x</p></div>),或者从别处取出的 Tag:wrap(BeautifulSoup("<div>H</div>", "html.parser").div)(实测得到 <div>H<p>x</p></div>)。
    • 插入简单标签更稳的写法是不用字符串解析,直接 tag = soup.new_tag("img"); tag["src"] = "/img/1.png",实测得到 <div><img src="/img/1.png"/></div>;纯文本用 soup.new_string("b"),实测 <p>a</p> 追加后变 <p>ab</p>。

实战:列表页到详情页

movies.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import urllib.request

from bs4 import BeautifulSoup

BASE = "https://ssr1.scrape.center"
HEADERS = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/156.0"}


def soup_of(path):
req = urllib.request.Request(BASE + path, headers=HEADERS)
with urllib.request.urlopen(req, timeout=20) as r:
return BeautifulSoup(r.read(), "lxml") # 直接给 bytes,让 bs4 看 meta 猜编码


cards = soup_of("/page/2").select("div.el-card.item")
for card in cards:
print("%s / %s / %s" % (
card.select_one("a.name").h2.string,
card.select_one("p.score").get_text(strip=True),
card.select_one("a.name")["href"]))

for card in cards[:3]:
href = card.select_one("a.name")["href"]
detail = soup_of(href)
infos = detail.select("div.info")
print("%s | %s | %s | 导演 %s | 演员 %d 人" % (
detail.h2.string,
infos[0].get_text("", strip=True),
infos[1].get_text("", strip=True),
detail.select_one(".director").get_text(strip=True),
len(detail.select(".actor"))))
1
2
3
4
5
6
7
8
9
10
11
12
13
V字仇杀队 - V for Vendetta / 8.9 / /detail/11
少年派的奇幻漂流 - Life of Pi / 8.9 / /detail/12
美丽心灵 - A Beautiful Mind / 8.8 / /detail/13
初恋这件小事 - สิ่งเล็กเล็กที่เรียกว่า...รัก / 8.9 / /detail/14
借东西的小人阿莉埃蒂 - 借りぐらしのアリエッティ / 8.8 / /detail/15
一一 - Yi yi: A One and a Two / 8.8 / /detail/16
美丽人生 - La vita è bella / 9.1 / /detail/17
海上钢琴师 - La leggenda del pianista sull'oceano / 9.1 / /detail/18
千与千寻 - 千と千尋の神隠し / 9.1 / /detail/19
迁徙的鸟 - The Travelling Birds / 9.1 / /detail/20
V字仇杀队 - V for Vendetta | 美国、英国、德国/132 分钟 | 2005-12-11 上映 | 导演 詹姆斯·麦克特格 | 演员 96 人
少年派的奇幻漂流 - Life of Pi | 美国、中国台湾、英国、加拿大/127 分钟 | 2012-11-22 上映 | 导演 李安 | 演员 43 人
美丽心灵 - A Beautiful Mind | 美国/135 分钟 | 2001-12-13 上映 | 导演 朗·霍华德 | 演员 111 人
  • 五个要点:
    • select_one 找不到返回 None,链式取文本就会 AttributeError,实测 card.select_one("p.price").string 报 'NoneType' object has no attribute 'string'。
    • 详情页只有 div.info 是稳定两个,第一个装「地区 / 时长」,第二个装「上映日期」。
    • .actor 的数量在每个详情页差一个数量级,实测霸王别姬 30 个、美丽心灵 111 个,不能当定长字段用。
    • 分页 URL 不带尾斜杠,实测 /page/2 是 200、/page/2/ 是 404。
    • bs4 只看得到静态 HTML:同一套选择器换到 https://spa1.scrape.center/ 上取到 0 张卡片,那个首页只有 952 字节。

三种解析方式怎么选

需求 推荐 原因
结构化字段(标签、属性、层级) BeautifulSoup 容错、可读,属性顺序变了不影响
复杂层级与轴(父、兄弟、后代) XPath,见《爬虫-XPath》 表达式比 CSS 强,能按文本条件定位
纯文本里抽字段(手机号、日期、金额) 正则,见《爬虫-正则》 已经不是「文档」而是「串」
页面是 ajax 动态填的 先找接口,实在不行上 Selenium bs4 只看得到静态 HTML
  • 实测对照:同一个 src="a" alt="b" 属性顺序一变,正则 <img src="a" alt="b"> 什么都取不到,而 soup.select_one('img[alt="b"]') 照样命中。结构问题交给解析器,文本问题交给正则。

参考

本文结束 感谢您的阅读
正在加载今日诗词....