您的位置:首页 > 编程语言 > Python开发

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.

Introduction

The lxml XML toolkit is a Pythonic binding for the C libraries
libxml2 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.

还支持python 3.3,不错的。

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: