繁体   English   中英

使用LXML获取所有HTML元素

[英]Get all HTML elements using LXML

我试图解析一个大div我的HTML文档中的标签,并且需要将内部所有的HTML和嵌套标签div 我的代码:

innerTree = fromstring(str(response.text))
print("The tags inside the target div are")
print innerTree.cssselect('div.story-body__inner')

但它打印:

[<Element div at 0x66daed0>]

我希望它返回其中的所有HTML标记吗? 如何使用LXML做到这一点?

LXML是一个很棒的库。 无需使用BeautiulSoup或其他任何工具。 以下是获取所需额外信息的方法:

# import lxml HTML parser and HTML output function
from __future__ import print_function
from lxml.html import fromstring
from lxml.etree import tostring as htmlstring

# test HTML for demonstration
raw_html = """
    <div class="story-body__inner">
        <p>Test para with <b>subtags</b></p>
        <blockquote>quote here</blockquote>
        <img src="...">
    </div>
"""

# parse the HTML into a tree structure
innerTree = fromstring(raw_html)

# find the divs you want
# first by finding all divs with the given CSS selector
divs = innerTree.cssselect('div.story-body__inner')

# but that takes a list, so grab the first of those
div0 = divs[0]

# print that div, and its full HTML representation
print(div0)
print(htmlstring(div0))

# now to find sub-items

print('\n-- etree nodes')
for e in div0.xpath(".//*"):
    print(e)

print('\n-- HTML tags')
for e in div0.xpath(".//*"):
    print(e.tag)

print('\n-- full HTML text')
for e in div0.xpath(".//*"):
    print(htmlstring(e))

请注意, cssselectxpath类的lxml函数会返回节点列表,而不是单个节点。 您必须索引这些列表以获取包含的节点-即使只有一个。

要获取所有子标签或子HTML,可能意味着几件事:获取ElementTree节点,获取标签名称或获取这些节点的完整HTML文本。 此代码演示了这三个示例。 通过使用XPath查询来实现。 有时CSS选择器更方便,有时是XPath。 在这种情况下,XPath查询.//*意思是“在当前节点下以任何深度返回具有任何标签名称的所有节点。”

在Python 2下运行此代码的结果如下。 (尽管输出文本略有不同,但相同的代码在Python 3下运行良好,因为etree.tostring返回字节字符串而不是Python 3下的Unicode字符串。)

<Element div at 0x106eac8e8>
<div class="story-body__inner">
        <p>Test para with <b>subtags</b></p>
        <blockquote>quote here</blockquote>
        <img src="..."/>
    </div>


-- etree nodes
<Element p at 0x106eac838>
<Element b at 0x106eac890>
<Element blockquote at 0x106eac940>
<Element img at 0x106eac998>

-- HTML tags
p
b
blockquote
img

-- full HTML text
<p>Test para with <b>subtags</b></p>
<b>subtags</b>
<blockquote>quote here</blockquote>  
<img src="..."/>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM