8

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()?

shafty
  • 599
  • 6
  • 17

3 Answers3

1

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

Ricky Sahu
  • 19,709
  • 4
  • 38
  • 30
  • Great idea! Here's a probably too long list comprehension to do that: `dict((name.strip(), val.strip()) for name, val in (pair.split(':') for pair in pq.attr('style').split(';')))` where `p` is an instance of `PyQuery` – driftcatcher Jun 12 '13 at 14:56
1

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.

Nick Tomlin
  • 25,904
  • 10
  • 55
  • 84
1

p.css.font_size

Does this work?

VoronoiPotato
  • 2,888
  • 17
  • 30
  • I was really hoping the underscore would fix it :(. – VoronoiPotato Feb 17 '11 at 23:08
  • perhaps p.css('fontSize') might work? The camel case style works in jQuery, perhaps it will work here. – VoronoiPotato Feb 17 '11 at 23:33
  • That didn't work either. I looked into the pyquery code and it just returns self. Maybe I should contact the author about the matter. Is it worth sending him the code I added to get css() to return the value? – shafty Feb 18 '11 at 15:41
  • I didn't send it to him. I just ended up writing a simple function to return the css value by using split() on attr('css') and grabbing the appropriate value. I figure a lot of these packages are in a state of flux, what with python 3 coming soon. – shafty Feb 23 '11 at 19:02