lxml提取某个外层标签里的所有文本

html如下

html 复制代码
<div data-v-1cf6f280="" class="analysis-content">
    选项D错误:
    <strong>在衡量通货膨胀时,</strong>
    <strong>消费者物价指数使用得最多、最普遍</strong>
    。
</div>

解析html文本

python 复制代码
from lxml import etree
html1 = '''
<div data-v-1cf6f280="" class="analysis-content">
    选项D错误:
    <strong>在衡量通货膨胀时,</strong>
    <strong>消费者物价指数使用得最多、最普遍</strong>
    。
</div>
'''

html = etree.HTML(html1)

方法一:join

python 复制代码
s1 = html.xpath('//div/text()')

# 去掉空格和换行符
s11 = [x.strip() for x in s1]
print('div标签文本:',s1);print('div标签文本去掉空格和换行符:',s11)
s2 = html.xpath('//strong/text()')
print('strong标签文本',s2)
s3 = ''.join(s2)
s11[1] = s3
s = ''.join(s11)

print('拼接后:\n',s)

方法二:遍历父子节点

python 复制代码
def extract_text(element):
    text = []

    # 获取当前元素的文本(不包括子元素)
    if element.text:
        text.append(element.text.strip())

    # 遍历所有子元素,递归提取
    for child in element:
        text.extend(extract_text(child))  # 递归调用处理子元素

    # 获取当前元素尾部的文本(如果有)
    if element.tail:
        text.append(element.tail.strip())

    return text


# 获取<div>标签内的所有文本内容
text_list = extract_text(html)

# 拼接所有文本并输出
final_text = ''.join(text_list)
print("拼接后的文本:\n", final_text)
相关推荐
刘发财39 分钟前
弃用html2pdf.js,这个html转pdf方案能力是它的几十倍
前端·javascript·github
牛奶3 小时前
2026年大模型怎么选?前端人实用对比
前端·人工智能·ai编程
牛奶3 小时前
前端人为什么要学AI?
前端·人工智能·ai编程
Kagol6 小时前
🎉OpenTiny NEXT-SDK 重磅发布:四步把你的前端应用变成智能应用!
前端·开源·agent
GIS之路7 小时前
ArcGIS Pro 中的 notebook 初识
前端
JavaGuide7 小时前
7 道 RAG 基础概念知识点/面试题总结
前端·后端
ssshooter7 小时前
看完就懂 useSyncExternalStore
前端·javascript·react.js
孟健8 小时前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
格砸8 小时前
从入门到辞职|从ChatGPT到OpenClaw,跟上智能时代的进化
前端·人工智能·后端
Live000009 小时前
在鸿蒙中使用 Repeat 渲染嵌套列表,修改内层列表的一个元素,页面不会更新
前端·javascript·react native