You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用BeautifulSoup提取选中节点内i.ab与span.at的文本内容?

提取BeautifulSoup中特定子节点的文本内容

你已经成功定位到目标<li>元素了,接下来只需要在每个<li>里精准抓取<i class="ab">和<span class="at">的文本内容就行。这里给你调整后的代码:

from urllib.request import urlopen
from bs4 import BeautifulSoup

current_page = urlopen(url)
current_soup = BeautifulSoup(current_page, 'html.parser')
derivative_list = current_soup.select('p.dsm + ul.also li')

for li in derivative_list:
    # 用select_one匹配单个子元素,获取文本时去掉前后空白
    ab_word = li.select_one('i.ab').get_text(strip=True)
    ab_category = li.select_one('span.at').get_text(strip=True)
    # 按你要的格式输出
    print(f"{ab_word}, {ab_category}")

代码说明:

  • .select_one('selector'):和你用的.select()逻辑一致,只是返回匹配到的第一个元素,刚好适合每个<li>里只有一个目标<i>和<span>的情况
  • .get_text(strip=True):不仅能提取元素的文本内容,还会自动去除文本前后的空格、换行符,让输出更整洁

运行这段代码后,就能得到你想要的输出:

abdrea, groups
shokdia, techs

内容的提问来源于stack exchange,提问作者coure2011

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:40:45