zoukankan      html  css  js  c++  java
  • python中用lxml解析html

    lxml,是python中用来处理xml和html的功能最丰富和易用的库。详情见:http://lxml.de/index.html

    在windows下安装lxml,可以用easy_install工具,也可以直接安装二进制文件。为了方便,我选择直接用二进制方式安装。

    二进制文件的下载页面:https://pypi.python.org/pypi/lxml/3.4.1

    选择合适的版本,因我的系统是win7,64位,python版本为2.7,所以我选择如下lxml版本。

    安装完成后,就可以开始python代码了:

    import codecs
    import sys
    from lxml import etree
    
    tree = etree.HTML(open('d:\GitHub\python27\simple.html','r').read())
    
    nodes = tree.xpath("//div[@id='name']")
    print(nodes[0]).text

    用到的html文件:

    <!DOCTYPE html>
    <html>
    <head>
    <title>This is a simple html file</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    </head>
    <body>
    <div id="container">
        <div id="name" class="item">勇者面码</div>
        <div id="sex"></div>
        <div id="borth">9.18</div>
    </div>
    </body>
    </html>

    用lxml来解析,不会因为文档头小写而解析失败。

    我们仍未知道那天所看见的花的名字
  • 相关阅读:
    context-annotation
    bean-annotation
    K-means算法
    基于概率的分类-贝叶斯分类
    Application
    ConfigurableApplicationContext
    相关性分析
    方差分析
    Java 大写金额转换成数字
    linux 遍历文件添加index
  • 原文地址:https://www.cnblogs.com/menma/p/4190919.html
Copyright © 2011-2022 走看看