【发布时间】:2020-06-13 02:46:30
【问题描述】:
我有以下带有 CSS 玩具的 HTML 示例。
<html lang="en">
<head>
<style>
p {
font-family: 'Trebuchet MS', 'Lucida Sans Unicode', 'Lucida Grande', 'Lucida Sans', Arial, sans-serif;
}
.cl0 {
background-color: coral;
}
.cl1 {
position: absolute;
width: auto;
margin: 0 auto;
}
p > span {
color:cyan;
}
#id0::before {
content: "♥";
}
#id1::after {
content: " \21E6";
}
.art0 {
position: absolute;
left: 10em;
}
</style>
</head>
<body>
<div class="cl1">
<p class="cl0">
Story <span id="id0">Numbawan</span>
</p>
<article class="art0">
Story <span id="id1">Numbatu</span>
</article>
</div>
</body>
</html>
浏览器可以处理 CSS 样式并将其应用于任何元素。但是有没有办法(库)在 python 中做同样的事情并输出类似于 BeautifulSoup 但每个元素都有一个 property 将包含其已解析的完整样式?
for span in soup.find_all('span'):
print(span.string,'--', span.style)
=====================
Numbawan--content: "♥";background-color: coral;font-family: 'Trebuchet MS', 'Lucida Sans Unicode', 'Lucida Grande', 'Lucida Sans', Arial, sans-serif;color:cyan;
Numbatu--content: " \21E6";position: absolute;left: 10em;
我的意思不仅是上面的示例,我可能可以硬编码,而是对于任何具有现代网页大量样式表的复杂样式?我知道有硒在引擎盖下用铬渲染页面,但它是否允许按照我描述的方式查看每个元素样式? 我会很感激任何提示如何处理它。
【问题讨论】:
-
Beautiful Soup 正如您所暗示的那样,引擎盖下没有硒;它是 xml/html 文档的解析器。但是,如果您愿意使用 selenium 并启动浏览器,那么您想要实现的目标肯定是可行的;需要帮助吗?
-
我想让它以编程方式准备好,即这样我就可以在文档树中的任何地方找到具有自己的 CSS 属性的任何元素,即继承、默认等。我不真的需要 BeautifulSoup 或任何特定的东西。我只是希望能够拥有一个可以随意查询的结构并获取具有相应属性的元素,类似于 Chrome 在其样式部分中显示的内容,但有点简化。
-
那么,浏览器还会启动吗?是否可以在后台使用浏览器的驱动程序来完成所有繁重的工作,以便我以某种简化的结构将文档解析到 python 环境中?
标签: python html css selenium beautifulsoup