代码之家  ›  专栏  ›  技术社区  ›  Kevin

Python打印来自lxml html的元素

  •  8
  • Kevin  · 技术社区  · 10 年前

    试图打印出从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
    

    我得到的输出是

    Quote [<Element span at 0x1044db788>]
    

    但我想打印出该元素以进行故障排除。

    1 回复  |  直到 10 年前
        1
  •  15
  •   furas    5 年前

    有功能 tostring() 在里面 lxml.html

    import lxml, lxml.html
    
    print( lxml.html.tostring(element) )
    

    xpath 返回列表,因此必须使用 [0] 只获取第一个元素

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

    或 for 循环以分别处理每个元素

    for x in quote:
        print( 'Quote', html.tostring(x) )