【问题标题】:how to parse iframe in lxml in python?如何在python中解析lxml中的iframe?
【发布时间】:2014-03-27 03:28:31
【问题描述】:

我发现 lxml 无法解析 iframe 的 heml 元素。

import lxml.html
from urllib.request import urlopen
import os
url="http://news.163.com/special/mhmingdan/?bdsj"
file=urlopen(url).read()
root=lxml.html.document_fromstring(file)
tab=root.xpath('//iframe')

如何让lxml获取iframe的html元素?

【问题讨论】:

    标签: python html web-scraping lxml lxml.html


    【解决方案1】:

    您应该使用正斜杠// 而不是反斜杠\\

    tab = root.xpath('//iframe')
    

    此外,您可以通过将urlopen 结果直接传递给parse() 来简化获取页面和解析:

    root = lxml.html.parse(urlopen(url))
    

    【讨论】:

    • 我已经更正了,但是为什么我无法获取 iframe?
    • @it_is_a_literature 首先,您不应该编辑问题。此外,如果您打印出tab,您将看到iframe 元素已找到。
    • iframe下有个table节点,为什么取不到?
    【解决方案2】:
    page = requests.get(url)  
    tree = html.fromstring(page.content)
    src_url = tree.cssselect("iframe") 
    print src_url[0].attrib
    

    【讨论】:

      猜你喜欢
      • 2012-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-17
      • 1970-01-01
      • 1970-01-01
      • 2012-06-10
      • 1970-01-01
      相关资源
      最近更新 更多