爬虫-正则

这篇讲什么

  • 把 re 模块的元字符、数量修饰、分组引用、贪婪与非贪婪、五个常用函数逐个跑一遍,每条都带本机实测结果。
  • 重点讲两类翻车:贪婪 .* 把整页吃穿,以及用正则解析 HTML 时属性顺序一变就什么都取不到。
  • 最后给一个能整段复制的实战:从 scrape.center 的电影站列表页取名称、评分与详情链接,再从详情页取地区和上映日期,写成 HTML 文件。

单字符

  • 拿这条文本做实验:a1_ 中文测试 abc123(下面简称 T)。

    写法 含义 在 T 上的 findall
    . 除换行外的任意一个字符 a. → ['a1', 'ab', 'at']
    \d 数字 [0-9],默认也认全角数字 a\d → ['a1']
    \D 非数字 a\D → ['ab', 'at']
    \w 字母、数字、下划线,以及中文 a\w → ['a1', 'ab', 'at']
    \W 非 \w a\W → [](_ 属于 \w,所以匹配不到)
    \s 空白(空格、制表、换行) a\s → []
    \S 非空白 a\S → ['a1', 'ab', 'at']
    [aoe] 集合内任一字符 a[aoe] → []
    [a-w] 范围内任一字符 a[a-w] → ['ab', 'at']
    [^0-9] 取反 a[^0-9] → ['ab', 'at']
  • 两条最容易记错的:

    • \w 匹配中文。Python 3 默认带 re.UNICODE 标志(实测 re.compile(r"\d+").flags 就是 32),所以「下划线字母数字」这条老说法不完整。
    • . 不匹配换行,这是下面 re.S 那个坑的根源。
  • 元字符本身要转义,实测 1.2 这个模式在 "1x2 1.2" 上匹配到 2 个,写成 1\.2 才是 1 个。字符串来自外部时别自己数反斜杠,用 re.escape:实测 re.escape("a.b*c") 得到 a\.b\*c,能原样匹配回 a.b*c。

数量修饰

  • 在 "gooo od go g" 上实测 go* 系列:

    写法 含义 实测结果
    * 0 次或多次 ['gooo', 'go', 'g']
    + 至少 1 次 ['gooo', 'go']
    ? 0 或 1 次 ['go', 'go', 'g']
    {2} 正好 2 次 ['goo']
    {1,} 至少 1 次(等价 +) ['gooo', 'go']
    {1,3} 1 到 3 次,贪婪时先吃满 ['gooo', 'go'](gooo 是 3 个 o,多出的 1 个不回头)
  • ? 跟在数量词后面就是「非贪婪」开关,这层含义和「0 或 1 次」完全不同,是新手最容易混的一处,见下一节。

边界

  • 测试文本是多行的:love she\nlove her\nhate it。

    boundary.py
    1
    2
    3
    4
    5
    6
    7
    8
    9
    import re

    text = "love she\nlove her\nhate it"
    print(re.findall(r"^love", text))
    print(re.findall(r"^love", text, re.M))
    print(re.findall(r"her$", text))
    print(re.findall(r"her$", text, re.M))
    print(re.findall(r"\blove\b", text))
    print(re.findall(r"\Blove", text))
    1
    2
    3
    4
    5
    6
    []
    ['love', 'love']
    []
    ['her']
    ['love', 'love']
    []
    • ^ 和 $ 默认只对齐整串的开头和结尾,要按行匹配必须加 re.M。老笔记里「^ 以某某开头」这句话少说了这个前提。
    • \b 是「单词边界」,love 前后是空格/换行都算边界;\B 反过来,所以第二行里的 love 不满足 \Blove(它前面是换行,属于边界)。

分组、引用与命名组

  • 分组是「一个整体」,编号从 1 开始,0 永远是整段匹配。实测:

    groups.py
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    import re

    tag = "<p><div><span>猪八戒</span></div></p>"
    m = re.search(r"<(\w+)><(\w+)>\w+</\2></\1>", tag)
    print(m.group(0))
    print(m.groups())
    m2 = re.search(r"<(?P<tag>\w+)>(?P<txt>[^<]+)", tag)
    print(m2.group("tag"), "|", m2.groupdict())
    print(re.findall(r"(?:ab){2}", "abab cd"), re.findall(r"(ab){2}", "abab cd"))
    print(re.findall(r"(\w+)-(\w+)", "a-b c-d"))
    1
    2
    3
    4
    5
    <div><span>猪八戒</span></div>
    ('div', 'span')
    span | {'tag': 'span', 'txt': '猪八戒'}
    ['abab'] ['ab']
    [('a', 'b'), ('c', 'd')]
    • \1 \2 是引用前面分组匹配到的内容,不是「字符 1」。上面这条正则能同时校验开闭标签成对,靠的就是它。
    • findall 的返回值有个反直觉规则:有一个组时返回组的内容,有多个组时返回元组列表,整段匹配反而拿不到。要整段就用 finditer。
    • (?:...) 不占编号也不参与 findall,纯分组时用它能少踩上面那条坑。
  • 零宽断言(只判断位置,不吃字符)实测:

    lookaround.py
    1
    2
    3
    4
    5
    import re

    print(re.findall(r"\w+(?=_)", "a1_ abc")) # 前瞻:后面必须是 _
    print(re.findall(r"(?<=_)\w+", "a1_ abc")) # 后顾:前面必须是 _
    print(re.findall(r"(?!^)\d+", "12a34")) # 负向前瞻:只挡住开头
    1
    2
    3
    ['a1']
    []
    ['2', '34']
    • 第二条为什么是空:_ 后面紧跟的是空格,\w+ 匹配不到。想取 _ 后面的词得写 (?<=_)\w+ 配 "_abc" 这种串。
    • 第三条不是只取到 34:(?!^) 只否掉「位置 0」,所以 12 从第 2 个字符起又被匹配一次,结果是 ['2', '34']。断言判断的是位置,不是「跳过一次」。
  • 匹配对象上能取的东西:m.group() / m.groups() / m.groupdict() / m.start() / m.end() / m.span(),实测 re.search(r"\d+", "a12b") 的 span() 是 (1, 3)。

  • ⚠️ match / search 失败返回 None,不是空对象。所以 re.match(...).group() 这种写法在没匹配上时必然 AttributeError: 'NoneType' object has no attribute 'group',正确写法是先判断或 re.search(...) or 默认值。

贪婪与非贪婪

  • 同一份 HTML,.* 与 .*? 的差别是「吃穿」和「正好」:

    greedy.py
    1
    2
    3
    4
    5
    6
    import re
    import urllib.request

    html = urllib.request.urlopen("http://127.0.0.1:8010/lazy", timeout=10).read().decode()
    print(re.findall(r'src="(.*?)"', html)[:4])
    print(re.findall(r'src="(.*)"', html)[:1])
    1
    2
    ['/img/1.png', '', '/img/2.png', '']
    ['/img/1.png" src="" alt="第 1 张']
    • 非贪婪那条里出现的空串是 src=""(懒加载占位),不是 bug;贪婪那条直接把同一个标签里后面的属性吃进来了。
  • 嵌套结构是正则的死穴,实测:

    nested_div.py
    1
    2
    3
    4
    5
    import re

    text = '<div class="neirong"><p>第一段</p><div class="neirong">嵌套</div></div>'
    print("文本:" + text)
    print("非贪婪取到:" + str(re.findall(r'<div class="neirong">(.*?)</div>', text)))
    1
    2
    文本:<div class="neirong"><p>第一段</p><div class="neirong">嵌套</div></div>
    非贪婪取到:['<p>第一段</p><div class="neirong">嵌套']

    取到的是「到第一个 </div> 为止」,正好把内层标签切一半。页面里只要可能出现同名标签嵌套,就不该用正则取内容,改用 BeautifulSoup 或 XPath。

五个函数与两个替换

函数 行为 实测要点
re.match(pat, s) 只从串首匹配 re.match(r"b", "abc") → None
re.search(pat, s) 全串找第一个 re.search(r"b", "abc") → b
re.fullmatch(pat, s) 整串必须匹配 fullmatch(r"\d+","123") True,"12a" False
re.findall(pat, s) 返回列表(有组时返回组) 见上一节
re.finditer(pat, s) 返回匹配对象迭代器 [m.group() for m in re.finditer(r"\d+","a12b345")] → ['12','345']
re.sub(pat, new, s) 替换,返回字符串 re.sub(r"<img .*?>", "", '<p><img src="a.png">正文</p>') → <p>正文</p>
re.subn(pat, new, s) 替换并返回 (结果, 次数) re.subn(r"\s+", " ", "a b\tc") → ('a b c', 2)
  • 替换串里引用分组:\2 是第 2 组,但组号后面还能接数字时必须写 \g<1>,实测:

    sub_ref.py
    1
    2
    3
    4
    5
    6
    7
    8
    9
    import re

    print(re.sub(r"(\w+) (\w+)", r"\2 \1", "love her"))
    print(re.sub(r"(\w+)", r"\g<1>0", "ab"))
    print(re.sub(r"a", "X", "aaaa", count=2))
    try:
    re.sub(r"(\w+)", r"\10", "ab")
    except Exception as e:
    print(type(e).__name__, e)
    1
    2
    3
    4
    her love
    ab0
    XXaa
    PatternError invalid group reference 10 at position 1
    • 最后一条就是「\1 后面跟数字」的撞车现场:\10 被当成第 10 组,而这里只有 1 个组,直接报错。写成 \g<1>0 才是「第 1 组 + 字符 0」。
  • 替换值要动态计算就传函数,实测 re.sub(r"\d", lambda m: str(int(m.group()) * 2), "a1b23") → a2b46。

  • ⚠️ 模块级 re.findall(pat, s, pos=1) 不支持 pos 参数,实测 TypeError: findall() got an unexpected keyword argument 'pos';pos/endpos 只有编译后的对象才有:re.compile(r"\w").findall("abcd", pos=1) → ['b', 'c', 'd']。

常用 flag

  • 实测五个:

    flags.py
    1
    2
    3
    4
    5
    6
    7
    8
    9
    import re

    text = "love she\nLOVE her"
    print(re.findall(r"LOVE", text, re.I))
    print(re.findall(r"^love", text, re.M))
    multi = "<div>北国风光\n千里冰封</div>\n<div>万里雪飘</div>"
    print(re.findall(r"<div>(.*)</div>", multi))
    print(re.findall(r"<div>(.*)</div>", multi, re.S))
    print(re.findall(r"\d", "123", re.A), re.findall(r"\d", "123"))
    1
    2
    3
    4
    5
    ['love', 'LOVE']
    ['love']
    ['万里雪飘']
    ['北国风光\n千里冰封</div>\n<div>万里雪飘']
    ['3'] ['1', '2', '3']
    flag 作用 上面的对应结果
    re.I 忽略大小写 小写模式能匹配大写
    re.M ^ $ 按行生效 只匹配到第一行开头
    re.S . 连换行也吃 不带 S 时只能拿到最后一个 div
    re.X 忽略模式里的空白与 # 注释,便于写长正则 带注释的模式照样匹配
    re.A 让 \d \w 只认 ASCII 全角数字 12 不再算数字
  • 「不带 re.S 时 <div>(.*)</div> 只拿到 万里雪飘」这条值得记住:跨行标签必须加 re.S,否则第一个 </div> 之前的换行会让匹配整段失败,于是只剩最后一行那个。

  • flag 也可以写在模式里:(?i)、(?s)、(?m)、(?x),实测 re.sub(r"(?i)love (\w+)", r"hate \g<1>", "LOVE she") → hate she。

compile 与缓存

  • 同一条正则用第二次以上就 re.compile,可读性和速度都更好:

    compiled.py
    1
    2
    3
    4
    import re

    pat = re.compile(r'<li class="item" data-id="(\d+)">\s*<a class="title" href="([^"]+)">([^<]+)</a>', re.S)
    print(type(pat).__name__, pat.pattern[:20], pat.flags)
    1
    Pattern <li class="item" d 32
  • 模块级函数其实也带缓存,实测本机 re._MAXCACHE 是 512;临时跑 600 条不同模式后缓存停在 512(满了会淘汰旧的),re.purge() 之后归 0。

    • 结论:循环里动态拼正则(比如把用户输入拼进模式)会不断冲刷缓存,还会带来注入风险。要么固定模式,要么自己 lru_cache 一层,并且对拼进去的内容先 re.escape。

实战:取标题、链接和正文

  • 老笔记这道题是「爬取指定页面的标题和内容,保存成 HTML,标题用 h1、内容用 p」。这里换成 scrape.center 的电影站:Vue 服务端渲染,requests 拿到的 HTML 里就带数据,不用浏览器也不用接口。写法如下(列表页 → 详情页 → 落盘):

    save_html.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
    import re
    import urllib.request

    BASE = "https://ssr1.scrape.center"
    HEADERS = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
    "(KHTML, like Gecko) Chrome/156.0.0.0 Safari/537.36"}


    def fetch(path):
    req = urllib.request.Request(BASE + path, headers=HEADERS)
    with urllib.request.urlopen(req, timeout=20) as r:
    return r.read().decode("utf-8")


    # 卡片里 </a> 与 <h2> 之间有换行和缩进,评分又在十几个标签之后,靠 \s* 与 .*? 跨过去
    card_pat = re.compile(
    r'<a[^>]*href="(/detail/\d+)" class="name">\s*<h2[^>]*>(.*?)</h2>.*?'
    r'class="score[^"]*">\s*([\d.]+)', re.S)
    info_pat = re.compile(r'<div[^>]*class="m-v-sm info"[^>]*>(.*?)</div>', re.S)


    def strip_html(text):
    return re.sub(r"\s+", " ", re.sub("<[^>]+>", "", text)).strip()


    cards = card_pat.findall(fetch("/page/2"))
    print("第2页命中", len(cards), "条")

    out = []
    for href, title, score in cards[:3]:
    infos = [strip_html(x) for x in info_pat.findall(fetch(href))]
    out.append("<h1>%s</h1><p>%s|%s|%s|%s</p>" % (title, score, infos[0], infos[1], href))

    with open("movies.html", "w", encoding="utf-8") as f:
    f.write("\n".join(out))
    print("\n".join(out))
    1
    2
    3
    4
    第2页命中 10 条
    <h1>V字仇杀队 - V for Vendetta</h1><p>8.9|美国、英国、德国 / 132 分钟|2005-12-11 上映|/detail/11</p>
    <h1>少年派的奇幻漂流 - Life of Pi</h1><p>8.9|美国、中国台湾、英国、加拿大 / 127 分钟|2012-11-22 上映|/detail/12</p>
    <h1>美丽心灵 - A Beautiful Mind</h1><p>8.8|美国 / 135 分钟|2001-12-13 上映|/detail/13</p>
  • 这段里四个只能实测才知道的细节:

    • \s* 是用来吃换行的:把 class="name">\s*<h2 写成 class="name"><h2,同一份 HTML 命中从 10 条变成 0 条。
    • 列表页的片名是「中文 - 英文」一整串(V字仇杀队 - V for Vendetta),还要拆开就再补一刀:re.split(r" - ", title) → ['V字仇杀队', 'V for Vendetta']。
    • 分页 URL 不带尾斜杠:/page/2 是 200,/page/2/ 是 404;页码条一直列到 /page/11,但第 11 页实测 500 Server Error,照着页码条翻会在最后一页报错。
    • 别按 id 递增遍历详情页:这个站 count 写着 104,可列表页只给到 /detail/100,/detail/101 到 /detail/108 全是 500,能稳定取到的详情是 1–100。

什么时候别用正则

  • 实测三种「HTML 稍微一变就取不到」的情况:

    html_regex_fail.py
    1
    2
    3
    4
    5
    6
    7
    8
    import re

    img = '<img alt="b" src="a">'
    pat = r'<img src="a" alt="b">'
    print("属性顺序变了:%s 用 %s 去匹配 -> %s" % (img, pat, re.findall(pat, img)))
    print("标签大小写: <DIV> 用 <div> 不加 re.I ->",
    "不匹配" if re.search(r"<div>", "<DIV>") is None else "匹配")
    print("同名标签嵌套:见「贪婪与非贪婪」那节,非贪婪也会切进内层")
    1
    2
    3
    属性顺序变了:<img alt="b" src="a">     用 <img src="a" alt="b"> 去匹配 -> []
    标签大小写: <DIV> 用 <div> 不加 re.I -> 不匹配
    同名标签嵌套:见「贪婪与非贪婪」那节,非贪婪也会切进内层
  • 判断标准很简单:只要目标是「结构化文档里的某个字段」,就用解析器(《爬虫-BeautifulSoup》 或 《爬虫-XPath》),正则留给三件事——

    • 从已经取到的文本里再抽字段(手机号、日期、金额);
    • 清洗(去标签、压缩空白、替换);
    • 站点结构太乱、解析器也理不清时的兜底。

参考

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