4

Can someone explain why the first call to root.cssselect() works, while the second fails?

from lxml.html import fromstring
from lxml import etree

html='<html><a href="http://example.com">example</a></html'
root = fromstring(html)
print 'via fromstring', repr(root) # via fromstring <Element html at 0x...>
print root.cssselect("a")

root2 = etree.HTML(html)
print 'via etree.HTML()', repr(root2) # via etree.HTML() <Element html at 0x...>
root2.cssselect("a") # --> Exception

I get:

Traceback (most recent call last):
  File "/home/foo_eins_d/src/foo.py", line 11, in <module>
    root2.cssselect("a")
AttributeError: 'lxml.etree._Element' object has no attribute 'cssselect'

Version: lxml==3.4.4

2

1 Answer 1

3

The difference is in the type of element. Example -

In [12]: root = etree.HTML(html)

In [13]: root = fromstring(html)

In [14]: root2 = etree.HTML(html)

In [15]: type(root)
Out[15]: lxml.html.HtmlElement

In [16]: type(root2)
Out[16]: lxml.etree._Element

lxml.html.HTMLElement has the method cssselect() . Also, HTMLElement is a subclass of etree._Element .

But the lxml.etree._Element does not have that method.

If you want to parse html, you should use lxml.html.

Sign up to request clarification or add additional context in comments.

8 Comments

Is there a reason why cssselect() does not work on xml? I parse xml and would like to use css selectors instead of xpath. I can type css selectors fast since I use them often in jquery. While using xpath, I need to look up the reference every time :-(
because xml does not have a concept of css/cssselectors work based on specific attributes like class id style etc , xml does not have these kinds of attirbutes predefined , xml can have attirbutes. cssselectors only work on html.
Also, xpath is not that slower than cssselect, for the css selector 'a' you can give xpath as - '//a' .
XML has the attribute id. Most CSS selectors would work very well with xml. Example: mytag[myattr="myval"]
the equivalent xpath for that would be //mytag[@myattr="myval"] . Not much difference.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.