Search code examples
pythonlxml.html

Python Print element from lxml html


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.


Solution

  • 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) )