Saturday, February 13, 2010

Python and CSS Selector

Python has a lot of awesome modules for working with html documents. My favorite one is lxml modules. Last time I wrote about xpath using that module.
Now, it is time for css selector using lxml.cssselect.

Straight to an example of using it:

from lxml.cssselect import CSSSelector
css_sel = CSSSelector('table.tableSchedule tr')
html_doc = lxml.html.fromstring(some_web_html_string)
row_els = css_sel(html_doc)
print row_els


Sweet and simple.

I am still playing around with it and found that using direct descendant css code is not possible. Something like the following:

css_sel = CSSSelector('table.tableSchedule > tobdy > tr > td')


Please leave a comment if you are able to use ">" in the css code part.

Friday, February 12, 2010

django deep serializers

Django has it's own very nice serialization module. A very useful tool to serialize models in django projects. There is limitation to it, though.
When one serialize a model (table) which has relationship (ForeignKey) to other model, then you will only get the foreign_key, instead the whole object. Something like the following:

[ {
"pk": 1,
"model": "store.book",
"fields": {
"name": "Mostly Harmless",
"author": 42
}
} ]



In some cases, deep serializing is often necessary. Now, let me introduce you to this magnificent python module which extends django's built-in serializers. DjangoFullSerializers.
With this, you can get something like the following:

[ {
"pk": 1,
"model": "store.book",
"fields": {
"name": "Mostly Harmless",
"author": [ {
"pk": 42,
"model": "store.author",
"fields": {
"name": "John Doe",
"title": "Dr."
}
} ]
' }
} ]


I have used it and really satisfied with the result. Many thanks to the developer.

Thursday, February 4, 2010

Send key in Linux (Ubuntu)

I have a dell mini 9 laptop which only have Fn keys from F1 to F10. Sometimes I need F11 key for fullscreen browsing, and maybe even F12 key, but they are missing. This little thing annoys me, so I was thinking about a way to send key in Linux.
I did not want to install any other piece of software for this little thing. So, I was thinking about using what is already there in my Ubuntu (default) installation.
xte is just the tool that I needed.
To give you an example, here is the command to send F11 key to active window.

$ xte "key F11"


Pretty neat.

Notes: I just figured out to use F11 and F12 in dell mini 9. Use Fn+z for F11, Fn+x for F12. I tested both keys in Ubuntu 9.04.