Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting attributes in PyQuery?

Tags:

I'm using PyQuery and want to print a list of links, but can't figure out how to get the href attribute from each link in the PyQuery syntax.

This is my code:

  e = pq(url=results_url)   links = e('li.moredetails a')   print len(links)   for link in links:     print link.attr('href') 

This prints 10, then gives the following error:

AttributeError: 'HtmlElement' object has no attribute 'attr' 

What am I doing wrong?

like image 454
Richard Avatar asked Dec 28 '12 13:12

Richard


People also ask

How to get attributes in jQuery?

Get Attributes - attr() The jQuery attr() method is used to get attribute values.

How to get attribute name in jQuery?

To get the name, you'd use $(selector). attr('name') which would return (in your example) 'xxxxx' . Save this answer.

What is attr in javascript?

The attr() method sets or returns attributes and values of the selected elements. When this method is used to return the attribute value, it returns the value of the FIRST matched element.


2 Answers

PyQuery wraps lxml, so you use the ElementTree API to access attributes:

e = pq(url=results_url) for link in e('li.moredetails a'):     print link.attrib['href'] 

Alternatively, to use the PyQuery API on any found element, wrap the element in a pq() call, echoing the way you need to use jQuery $() or jQuery() to wrap DOM elements:

    print pq(link).attr('href') 

or

    print pq(link).attr['href'] 

for a more pythonic way to accessess the attributes.

You could also loop over the .items() method instead, which returns PyQuery elements instead:

e = pq(url=results_url) for link in e('li.moredetails a').items():     print link.attr['href'] 
like image 81
Martijn Pieters Avatar answered Sep 26 '22 00:09

Martijn Pieters


As in jQuery, wrap that link up:

e = pq(url=results_url) links = e('li.moredetails a') print len(links) for link in links:     print pq(link).attr('href') 
like image 24
Pavel Anossov Avatar answered Sep 22 '22 00:09

Pavel Anossov