etree.findall:'OR'-查找?

发布于 2024-08-26 02:32:21 字数 608 浏览 3 评论 0原文

我想使用 lxml.etree.findall 查找 XHTML 文件中的所有样式表定义。这可能很简单,

elems = tree.findall('link[@rel="stylesheet"]') + tree.findall('style')

但是 CSS 样式定义的问题在于顺序很重要,例如,

<link rel="stylesheet" type="text/css" href="/media/css/first.css" />
<style>body:{font-size: 10px;}</style>
<link rel="stylesheet" type="text/css" href="/media/css/second.css" />

如果 style 标记的内容在两个 link 中的规则之后应用标签,结果可能与按定义顺序应用规则的结果完全不同。

那么,我将如何进行包含 link[@rel="stylesheet"]style 的查找?

I want to find all stylesheet definitions in a XHTML file with lxml.etree.findall. This could be as simple as

elems = tree.findall('link[@rel="stylesheet"]') + tree.findall('style')

But the problem with CSS style definitions is that the order matters, e.g.

<link rel="stylesheet" type="text/css" href="/media/css/first.css" />
<style>body:{font-size: 10px;}</style>
<link rel="stylesheet" type="text/css" href="/media/css/second.css" />

if the contents of the style tag is applied after the rules in the two link tags, the result may be completely different from the one where the rules are applied in order of definition.

So, how would I do a lookup that inlcudes both link[@rel="stylesheet"] and style?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

若水微香 2024-09-02 02:32:21

可以使用 XPATH:

data = """<link rel="stylesheet" type="text/css" href="/media/css/first.css" />
<style>body:{font-size: 10px;}</style>
<link rel="stylesheet" type="text/css" href="/media/css/second.css" />
"""

from lxml import etree

h = etree.HTML(data)

h.xpath('//link[@rel="stylesheet"]|//style')

[<Element link at 97a007c>,
 <Element style at 97a002c>,
 <Element link at 97a0054>]

Possible using XPATH:

data = """<link rel="stylesheet" type="text/css" href="/media/css/first.css" />
<style>body:{font-size: 10px;}</style>
<link rel="stylesheet" type="text/css" href="/media/css/second.css" />
"""

from lxml import etree

h = etree.HTML(data)

h.xpath('//link[@rel="stylesheet"]|//style')

[<Element link at 97a007c>,
 <Element style at 97a002c>,
 <Element link at 97a0054>]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文