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)
相关推荐
weixin_514221851 小时前
FDTD与matlab、python耦合
python·学习·matlab·fdtd
SUPER52662 小时前
FastApi项目启动失败 got an unexpected keyword argument ‘loop_factory‘
java·服务器·前端
sanx182 小时前
专业电竞体育数据与系统解决方案
前端·数据库·apache·数据库开发·时序数据库
你的人类朋友4 小时前
【Node】认识一下Node.js 中的 VM 模块
前端·后端·node.js
Cosolar4 小时前
FunASR 前端语音识别代码解析
前端·面试·github
F_D_Z6 小时前
数据集相关类代码回顾理解 | StratifiedShuffleSplit\transforms.ToTensor\Counter
python·torchvision·transforms
@大迁世界7 小时前
Vue 设计模式 实战指南
前端·javascript·vue.js·设计模式·ecmascript
tao3556677 小时前
【Python刷力扣hot100】283. Move Zeroes
开发语言·python·leetcode
芭拉拉小魔仙7 小时前
Vue项目中如何实现表格选中数据的 Excel 导出
前端·vue.js·excel
jump_jump8 小时前
妙用 localeCompare 获取汉字拼音首字母
前端·javascript·浏览器