Python中尝试用lxml去解析html
2016-05-16 09:10
204 查看
【记录】Python中尝试用lxml去解析html
【背景】Python中,之前一直用BeautifulSoup去解析html的:
【教程】Python中第三方的用于解析HTML的库:BeautifulSoup
后来听说BeautifulSoup很慢,而lxml解析html速度很快,所以打算去试试lxml。
【折腾过程】
1.去lxml主页看了看简介:
lxml – XML and HTML with Python
lxml is the most feature-rich and easy-to-use library for processing XML and HTML in the Python language.IntroductionThe lxml XML toolkit is a Pythonic binding for the C librarieslibxml2 and libxslt. It is unique in that it combines the speed and XML feature completeness of these libraries with the simplicity of a native Python API, mostly compatible but superior to the well-known ElementTree API. The latest release works with all CPython versions from 2.4 to 3.3. See the introduction for more information about background and goals of the lxml project. Some common questions are answered in the FAQ. |
2.去Python lxml Packages
看到好多个版本,找了最新的一个:
lxml 3.2.1
此处是win7 x64,所以下载对应的:
lxml-3.2.1.win-amd64-py2.7.exe
然后继续安装lxml:
3.接下来,就是搞懂如何使用lxml去解析html了。
所以,先去找个,正常的html,比如之前的教程:
【教程】抓取网并提取网页中所需要的信息 之 Python版
中所涉及到的。
4.再参考一堆教程:
The lxml.etree Tutorial
用lxml解析HTML
最终,写成如下,可以正常运行的代码:
?
(1)关于lxml.etree._Element
可以在
http://lxml.de/api/index.html
中找到所有的api的解释。
其中就有我们所需要的:
find(self, path, namespaces=None) Finds the first matching subelement, by tag name or path. Properties attrib Element attribute dictionary. Where possible, use get(), set(), keys(), values() and items() to access element attributes. text Text before the first subelement. This is either a string or the value None, if there was no text. |
(2)关于find()的解释,参见:
Element.find(): Find a matching sub-element
(3)参考:
11. The art of Web-scraping: Parsing HTML with Beautiful Soup
去折腾了一下,结果是需要额外的BeautifulSoup库,才可以正常运行的。
【总结】
在Python中用lxml解析html,还是需要学习很多lxml中的库的用法的,包括对应的ElementTree等等。
其中:
1.关于教程方面,值得参考的是:
用lxml解析HTML
Elements and Element Trees
2.关于api方面,值得参考的是:
http://lxml.de/api/index.html
Python XML processing with lxml
http://lxml.de/FAQ.html#xpath-and-document-traversal
相关文章推荐
- python 信用卡系统+购物商城见解
- 浅谈Python 中整型对象的存储问题
- 使用python脚本,调用post方式监控服务器状态
- python学习笔记—使用dict和set
- python学习笔记—输入输出
- Python学习笔记—使用list和tuple
- Python学习笔记—字符串和编码
- Python学习笔记
- python基础-字典
- Python语法一
- 关于python字符串的处理
- python计算非内置数据类型占用内存
- Python 类(一)
- Python内置函数(一)
- python urllib, urllib2实现登陆和简单爬取网页(个人坑点笔记)
- Python笔记
- python 中__getattr__ 以及 __setattr__
- python正则表达式(个人笔记)
- python基础练习(六)—— 绘图与可视化
- 浅谈Python 中整型对象的存储问题