使用 LXML 获取所有 HTML 元素

Meh*_*hdi 3 html python parsing lxml

我正在尝试解析divHTML 文档中的一个大标签,并且需要获取其所有 HTML 和嵌套标签div。我的代码:

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

但它打印:

[<Element div at 0x66daed0>]
Run Code Online (Sandbox Code Playgroud)

我想让它返回里面所有的HTML标签?如何使用 LXML 做到这一点?

Jon*_*ice 5

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))
Run Code Online (Sandbox Code Playgroud)

请注意,和lxml等函数返回节点列表,而不是单个节点。您必须对这些列表进行索引才能获取包含的节点——即使只有一个。cssselectxpath

获取所有子标签或子 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="..."/>
Run Code Online (Sandbox Code Playgroud)