有没有一个库可以为我提供HTML页面中所有节点的XPATH?
是否有任何库可以给我HTML页面中所有节点的XPath?
是的,如果这个HTML页面是一个格式良好的XML文档。
取决于你对“节点”的理解……
//*
选择文档中的所有元素。
/descendant-or-self::node()
选择所有元素、文本节点、处理指令、注释节点和根节点 /
。
//text()
选取文档中的所有文本节点。//comment()
选择文档中的所有注释节点。
//processing-instruction()
选择文档中的所有处理指令。
//@*
选择文档中的所有属性节点。
//namespace::*
选择文档中的所有命名空间节点。
最后,您可以使用联合(|
)运算符组合上述任何表达式。
因此,我认为以下表达式确实选择了任何XML文档的“所有节点”:
/descendant-or-self::node() | //@* | //namespace::*
node()
,如ancestor::node()
或self::node()
。 - Dimitre Novatchevnode()
作为一种模式”。 - user357812import lxml
from lxml import html, etree
your_webpage_string = "<html><head><title>test<body><h1>page title</h3>"
root = lxml.html.fromstring(your_webpage_string)
good_html = etree.tostring(root, pretty_print=True).strip()
your_tree = etree.fromstring(good_html)
all_xpaths = your_tree.xpath('//*')
all_xpaths
是一个看起来像这样的列表:[<Element html at 0x7ff740b24b90>,
<Element head at 0x7ff740b24d88>,
<Element title at 0x7ff740b24dd0>,
<Element body at 0x7ff740b24e18>,
<Element h1 at 0x7ff740b24e60>]