9

Trying to print out the entire element retrieved from lxml.

from lxml import html
import requests

page=requests.get("http://finance.yahoo.com/q?s=INTC")
qtree = html.fromstring(page.content)

quote = qtree.xpath('//span[@class="time_rtq_ticker"]')

print 'Shares outstanding', Shares
print 'Quote', quote

The Output I get is

Quote [<Element span at 0x1044db788>]

But I'd like to print out the element for troubleshooting purposes.

Kevin
  • 93
  • 1
  • 4

1 Answers1

16

There is function tostring() in lxml.html

import lxml, lxml.html

print( lxml.html.tostring(element) )

xpath returns list so you have to use [0] to get only first element

print( 'Quote', html.tostring(quote[0]) )

or for loop to work with every element separatelly

for x in quote:
    print( 'Quote', html.tostring(x) )
furas
  • 134,197
  • 12
  • 106
  • 148
  • Thanks. Simplifies it and clears it up. Was trying to treat 'quote' as an element when it's a list. – Kevin Feb 02 '16 at 14:34
  • is there a way to do this using the html5parser method without the weird html:div stuff? from lxml import html from lxml.html.html5parser import fragment_fromstring html.tostring(fragment_fromstring('
    hi
    ')) # hi'
    – Steve Feb 27 '16 at 00:19
  • Is there an element method for printing it as a string? Something like `element.some_method()`? – Andreas Yankopolus Nov 15 '17 at 14:09
  • 1
    @AndreasYankopolus element has no special method for printing - you have `lxml.html.tostring(element)` for this. – furas Nov 15 '17 at 14:52