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)
相关推荐
花酒锄作田3 小时前
[python]argparse 包在聊天机器人中的应用
python
NiceCloud喜云5 小时前
Opus 4.8 的 Effort Control 怎么选:Low 到 Max 五档策略
android·java·大数据·前端·c++·python·spring
wordbaby6 小时前
React Native + RNOH:跨页面数据回传的最佳实践与避坑指南
前端·react native
丷丩6 小时前
MapLibre GL JS第22课:查看本地GeoJSON
前端·javascript·map·mapbox·maplibre gl js
AI玫瑰助手6 小时前
Python函数:默认参数的定义与注意事项
开发语言·python·信息可视化
weixin_468466856 小时前
全局与局部注意力机制新手实战指南
人工智能·python·深度学习·算法·自然语言处理·transformer·注意力机制
小糖学代码6 小时前
LLM系列:环境搭建:5.Python-dotenv 环境变量管理
人工智能·python·深度学习·神经网络
智慧物业老杨7 小时前
智慧物业合同周期管理系统:从风险预警到智能交接的全流程数智化落地方案
java·人工智能·python
Front思7 小时前
AI前端工程师需要具备能力+
前端·人工智能·ai
橙橙笔记7 小时前
Python的学习第一部分
python·学习