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)
相关推荐
万少23 分钟前
HarmonyOS官方模板集成创新活动-流蓝卡片
前端·harmonyos
-To be number.wan3 小时前
C++ 赋值运算符重载:深拷贝 vs 浅拷贝的生死线!
前端·c++
cnxy1883 小时前
围棋对弈Python程序开发完整指南:步骤4 - 提子逻辑和劫争规则实现
开发语言·python·机器学习
噢,我明白了3 小时前
JavaScript 中处理时间格式的核心方式
前端·javascript
TheSumSt4 小时前
Python丨课程笔记Part3:语法进阶部分(控制结构与基础数据结构)
数据结构·笔记·python
ha_lydms4 小时前
5、Spark函数_s/t
java·大数据·python·spark·数据处理·maxcompute·spark 函数
纸上的彩虹4 小时前
半年一百个页面,重构系统也重构了我对前端工作的理解
前端·程序员·架构
be or not to be5 小时前
深入理解 CSS 浮动布局(float)
前端·css
电商API&Tina5 小时前
跨境电商 API 对接指南:亚马逊 + 速卖通接口调用全流程
大数据·服务器·数据库·python·算法·json·图搜索算法
Yyyyy123jsjs5 小时前
外汇Tick数据交易时段详解与Python实战分析
人工智能·python·区块链