gawel / pyquery

A jquery-like library for python
http://pyquery.rtfd.org/
Other
2.3k stars 182 forks source link

The class type of element is different with that of the element collection #170

Closed sasrazor closed 7 years ago

sasrazor commented 7 years ago

For example: dom=pq("<html><body><div id='r1'></div><div id='r2'></div><div id='r3'></div></body></html>") divnodelist=dom('div') for divnode in divnodelist: print("class of divnode is "+type(divnode)) print("class of divnodelist is "+type(divnodelist))

The result is as follows: _class of divnode is <class 'lxml.etree.Element'> class of divnodelist is <class 'pyquery.pyquery.PyQuery'> ......

Due to the class of divnode is not PyQuery, I can not use the jquery related methods, such as: divnode.attr('id') When I use like the above, an error occurs:

AttributeError: 'lxml.etree._Element' object has no attribute 'attr'

An alternative right way is changing the class type of the divnode into PyQuery as follows:

divnode=pq(divnode) divnode.attr('id')

Though it's just an additional line, for a lazy guy who won't write one more letter, it's a trouble and not perfect.

My suggestion is, since the collection is a PyQuery collection, so for each element in the collection , its class should also be PyQuery.

gawel commented 7 years ago

Just use .items() http://pyquery.readthedocs.io/en/latest/api.html#pyquery.pyquery.PyQuery.items

sasrazor commented 7 years ago

Well, it's wonderful! Thanks very much! @gawel