爬虫--lxml获取节点所有子节点的文本

原文:

https://blog.csdn.net/qq_26235879/article/details/113090603

https://blog.csdn.net/weixin_33902301/article/details/118046434

from lxml import etree


def get_all_child_node_text():
    txt = """
    <div class="content">
        <p>输入只有一行半径r.</p>
    </div>
    <div class="content">
        <p>输出有多行,每一行是跟输入对应面积.</p>
        <p>输出保留6位小数</p>
    </div>
    """
    html = etree.HTML(txt)
    contents = html.xpath('//div[@class="content"]')
    lst = []
    for e in contents:
        # 第一种方式,通过使用xpath的string()方法
        # string(.)中的.代表当前节点
        # lst.append(e.xpath('string(.)').strip())
        # ['输入只有一行半径r.', '输出有多行,每一行是跟输入对应面积.
        输出保留6位小数']
        # lst.append(e.xpath('string(.)'))
        # ['
        输入只有一行半径r.
    ', '
        输出有多行,每一行是跟输入对应面积.
        输出保留6位小数
    ']
        # lst.append(e.xpath('string(.)').replace('
', '').strip())
        # ['输入只有一行半径r.', '输出有多行,每一行是跟输入对应面积.        输出保留6位小数']
        
        # 第二种方式使用lxml节点自带的方法itertext()
        # lst.append(''.join(e.itertext()))
        # ['
        输入只有一行半径r.
    ', '
        输出有多行,每一行是跟输入对应面积.
        输出保留6位小数
    ']
        lst.append(''.join(e.itertext()).replace('
', '').strip())
        # ['输入只有一行半径r.', '输出有多行,每一行是跟输入对应面积.        输出保留6位小数']
    print(lst)


if __name__ == '__main__':
    get_all_child_node_text()
View Code
原文地址:https://www.cnblogs.com/yarightok/p/15242725.html