Scrapy如何提取样式属性?

Jul*_*ang 3 python xpath scrapy

html 元素如下,

<div style="width: 80.42%;" class="classA"></div>
Run Code Online (Sandbox Code Playgroud)

使用此代码我可以提取整个样式元素:

response.xpath("//div[@class='classA']").xpath("@style").extract()
Run Code Online (Sandbox Code Playgroud)

但我想获取样式元素的宽度值,即80.42%,我该怎么办?

eLR*_*uLL 5

你可以使用cssutils,首先安装:

$ pip install cssutils
Run Code Online (Sandbox Code Playgroud)

然后在您的代码中使用它:

import cssutils
...

css_style = response.xpath("//div[@class='classA']/@style").extract()
parsed_css = cssutils.parseStyle(css_style)
print parsed_css.width # 80.42%
Run Code Online (Sandbox Code Playgroud)