selectolax比bs4快得多,因其底层用c编写的lexbor引擎直接解析html、跳过dom树构建中间层;而bs4依赖python实现的html.parser(慢)或启动重/内存高的lxml,实测解析10mb文件快8–12倍(vs html.parser)或1.5–3倍(vs lxml)。

为什么Selectolax比BS4快得多? Selectolax底层用C写的libhtml5parser,直接跳过DOM树构建的中间层,解析完就给节点对象;BS4默认用Python写的html.parser,或者依赖lxml(虽快但启动重、内存高)。实测10MB HTML文件,Selectolax通常比BS4 + html.parser快8–12倍,比BS4 + lxml也快1.5–3倍——尤其在大量嵌套标签或乱码HTML下优势更明显。
关键不是“语法像不像BS4”,而是它压根不模拟DOM标准:没有find_all()那种递归搜索,所有查找都是单次前序遍历,不缓存父链,也不自动修正标签闭合。这意味着你得自己处理“找不到就None”和“文本节点可能被拆成多个”的情况。
Selectolax基础用法:怎么加载和查元素?
安装只要pip install selectolax,没额外依赖。加载HTML和查元素非常轻量:
from selectolax.parser import HTMLParser
<p>html = "</p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill9263" title="Html2md"><img
src="https://img.php.cn/upload/skill/000/000/081/179249945220127.jpg" alt="Html2md" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/skill9263" title="Html2md" class="overflowclass">Html2md</a>
<p class="overflowclass">使用 Readability + Turndown 将 HTML 页面转换为干净的、Agent 友好的 Markdown。去除导航栏、广告、页脚、Cookie 横幅、社交按钮等干扰元素。支持 URL...</p>
</div>
<a rel="nofollow" href="/xiazai/skill9263" title="Html2md" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div><div class="item"><p>Hello</p></div>"
tree = HTMLParser(html)<h1>查第一个匹配节点(返回Node对象,不是列表)</h1><p>node = tree.css_first("div.item")
if node:
print(node.text()) # "Hello"
print(node.attributes.get("class")) # "item"</p><h1>查所有匹配节点(返回NodeList,支持len/for,但不支持索引)</h1><p>for p in tree.css("p"):
print(p.text())
</p>
注意三点:
-
css()和css_first()是主力方法,不支持BS4里的find()/find_all()别名 - 返回的
Node对象没有.parent或.next_sibling这种导航属性——要往上找得靠node.parent,但它只返回一个父节点,且可能为None -
node.text()默认会合并空白、去换行;要保留原始文本用node.text(strip=False)
常见踩坑:乱码、自闭合标签、动态内容怎么处理?
Selectolax默认按UTF-8解析,遇到<meta charset="gb2312">杩
Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!










