什么时候需要手动导航
多数场景下,CSS选择器或find_all直接定位到目标节点就够了。但有一类页面,目标数据的位置取决于上下文关系------比如"标题后面紧跟的那段价格文本",或者"某个特定标签的父级容器的兄弟节点里的字段"。这种定位依赖节点间关系,选择器写不出,就得手动在DOM树里走。
上下游走的基本接口
python
tag = soup.find("span", class_="anchor")
tag.parent # 直接父节点
tag.parents # 生成器,逐级向上到文档根
tag.next_sibling # 下一个兄弟节点
tag.previous_sibling # 上一个兄弟节点
tag.next_siblings # 后续所有兄弟节点(生成器)
tag.previous_siblings # 前面所有兄弟节点(生成器)
list(tag.children) # 直接子节点列表
list(tag.descendants) # 所有后代节点
这些接口的返回值要留意:.parent返回单个Tag对象或None,.children和.descendants返回迭代器,.next_sibling返回下一个节点(可能是NavigableString,不一定是Tag)。
兄弟节点导航的典型场景
页面里标题和价格在同一层级紧挨着,没有包裹容器,结构类似:
html
<h3 class="title">产品A</h3>
<span class="price">39元</span>
<h3 class="title">产品B</h3>
<span class="price">52元</span>
这种结构选择器写不了"每个标题后面跟的价格",但兄弟导航可以:
python
for title in soup.find_all("h3", class_="title"):
price = title.next_sibling
# next_sibling可能先碰到空白文本节点
while price and not hasattr(price, "get"):
price = price.next_sibling
if price and "price" in price.get("class", []):
print(title.get_text(strip=True), price.get_text(strip=True))
这里有个坑:HTML里的换行和缩进在解析后变成NavigableString,它们也是节点,算作兄弟节点。next_sibling可能先碰到一个纯空白文本节点,需要跳过。
父级回溯的策略
有些页面结构是"数据散落在多个同级标签里,共同被一个父容器包着"。直接全局find_all会捞到其他区域的同名标签。这时先定位一个特征明显的锚点,回溯到父容器,再在父容器内取值:
python
# 锚点:某个有唯一class的标题
anchor = soup.find("h2", class_="section-title")
# 回溯到最近的div容器
container = anchor.parent
while container and container.name != "div":
container = container.parent
# 容器内取所有字段
if container:
fields = container.find_all("span", class_="field")
for field in fields:
print(field.get_text(strip=True))
.parents生成器可以做更简洁的回溯:
python
for parent in anchor.parents:
if parent.name == "div" and "data-section" in parent.get("attrs", {}):
container = parent
break
next_siblings批量取同层后续数据
表格里某一行是表头,后续所有行是数据,且行之间没有特殊容器区分:
python
header = soup.find("tr", class_="header")
data_rows = []
for sibling in header.next_siblings:
if hasattr(sibling, "find_all") and sibling.name == "tr":
cells = sibling.find_all(["td", "th"])
data_rows.append([c.get_text(strip=True) for c in cells])
hasattr(sibling, "find_all")这个判断用来过滤掉NavigableString。兄弟节点可能是Tag也可能是文本节点,只有Tag才有find_all方法。不判断直接调用会抛AttributeError。
小结
手动导航的核心价值在于处理"依赖位置关系"的定位,这是选择器的死角。但导航代码比选择器难维护,可读性也差一截。我的原则是:选择器能写的不用导航,导航只在选择器够不到的地方补位。写导航代码时务必处理空白文本节点和类型判断,这是最容易遗漏的细节。