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?
Get Attributes - attr() The jQuery attr() method is used to get attribute values.
To get the name, you'd use $(selector). attr('name') which would return (in your example) 'xxxxx' . Save this answer.
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.
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']
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With