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)
相关推荐
aqi001 小时前
15天学会AI应用开发(八)使用向量数据库实现RAG功能
人工智能·python·大模型·ai编程·ai应用
Csvn2 小时前
`functools.lru_cache` —— 一行代码搞定缓存加速
后端·python
Csvn3 小时前
Monorepo 迁移血泪史:从 Multi-Repo 到 Turborepo,这 3 个坑我帮你踩完了
前端
星栈3 小时前
Dioxus 多页面怎么做:`dioxus-router`、嵌套路由、`Outlet` 和页面组织,一篇给你讲顺
前端·rust·前端框架
用户987409238873 小时前
用 Remotion + edge-tts 打造中文教学视频全自动流水线
前端
风骏时光牛马3 小时前
Less前端工程化实战:变量混合器与项目样式分层落地
前端
假如让我当三天老蒯3 小时前
Options API(选项式 API) 和 Composition API(组合式 API)
前端·vue.js·面试
SameX3 小时前
iOS 独立开发实践:用 MapKit + 像素渲染实现 Citywalk 轨迹地图 App「雁过留痕」
前端
skyey3 小时前
页面加载时,深色模式闪白的问题解决
前端