How to get an individual css style in pyquery

846 views Asked by At

You can set a css style using several methods:

p = PyQuery('<p></p>')
p.css('font-size','16px')
p.css(['font-size'] = '16px'
p.css = {'font-size':'16px'}

Great, but how to get an individual css style?

p.css('font-size') # jquery-like method doesn't work
[<p>]
p.css['font-size'] # pythonic method doesn't work!
[<p>]
p.css.font_size # BeardedO's suggestion.
[<p>]
p.attr('style')    # too much information.
'font-size: 16px; font-weight: bold'

This seems strange, inconvenient and unpyquery and unpython like! One of the first two ought to return the style text, surely?

Is there a way to get a single css style alone without resorting to tools like split()?

3

There are 3 answers

4
VoronoiPotato On

p.css.font_size

Does this work?

1
Ricky Sahu On

You could split the string and convert it into a dict.

0
Nick Tomlin On

It appears from your comment that you have already figured this out, but PyQuery does not provide this functionality.

The css method (line 824 in pyquery.py) only sets attributes and cannot retrieve, which is a shame. Although, given that PyQuery is not working with a stylesheet, the utility of retrieving CSS is limited anyway.

Manually sorting through the results of p.attr(style) seems to be the best way to go at the moment. I would like to see an option for retrieving css values if only one argument is passed to the css method, but we shall see.