roo*_*oot 6 html css python beautifulsoup
有没有办法使用BeautifulSoup从HTML文件中获取CSS类?示例代码段:
<style type="text/css">
p.c3 {text-align: justify}
p.c2 {text-align: left}
p.c1 {text-align: center}
</style>
Run Code Online (Sandbox Code Playgroud)
完美的输出将是:
cssdict = {
'p.c3': {'text-align':'justify'},
'p.c2': {'text-align:'left'},
'p.c1':{'text-align':'center'}
}
Run Code Online (Sandbox Code Playgroud)
虽然这样的事情会做:
L = [
('p.c3', {'text-align': 'justify'}),
('p.c2', {'text-align': 'left'}),
('p.c'1, {'text-align': 'center'})
]
Run Code Online (Sandbox Code Playgroud)
BeautifulSoup本身根本不解析CSS样式声明,但您可以提取这些部分,然后使用专用的CSS解析器解析它们.
根据您的需要,有几个CSS解析器可用于python; 我选择cssutils(需要python 2.5或更高版本(包括python 3)),它是最完整的支持,并且也支持内联样式.
要抓取并解析所有样式部分(使用cssutils的示例):
import cssutils
sheets = []
for styletag in tree.findAll('style', type='text/css')
if not styletag.string: # probably an external sheet
continue
sheets.append(cssutils.parseStyle(styletag.string))
Run Code Online (Sandbox Code Playgroud)
随着cssutil然后你可以结合这些,解决进口,甚至把它取外部样式表.
小智 5
BeautifulSoup 和 cssutils 组合可以很好地解决这个问题:
from bs4 import BeautifulSoup as BSoup
import cssutils
selectors = {}
with open(htmlfile) as webpage:
html = webpage.read()
soup = BSoup(html, 'html.parser')
for styles in soup.select('style'):
css = cssutils.parseString(styles.encode_contents())
for rule in css:
if rule.type == rule.STYLE_RULE:
style = rule.selectorText
selectors[style] = {}
for item in rule.style:
propertyname = item.name
value = item.value
selectors[style][propertyname] = value
Run Code Online (Sandbox Code Playgroud)
BeautifulSoup 解析 html (head & body) 中的所有“style”标签,.encode_contents() 将 BeautifulSoup 对象转换成 cssutils 可以读取的字节格式,然后 cssutils 解析各个 CSS 样式一直到属性/值通过 rule.selectorText 和 rule.style 设置级别。
注意: “rule.STYLE_RULE”仅过滤掉样式。该cssutils文档详细介绍了过滤介质的规则,意见和进口的选择。
如果你把它分解成函数会更清晰,但你明白了要点......
| 归档时间: |
|
| 查看次数: |
5573 次 |
| 最近记录: |