开放的编程资料库

当前位置:我爱分享网 > Python教程 > 正文

Python lxml

在本文中,我们展示了如何使用lxml库在Python中解析和生成XML和HTML数据。

lxml库为C库libxml2和libxslt提供Python绑定。

示例中使用了以下文件。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Words</title>
</head>
<body>

<ul>
    <li>sky</li>
    <li>cup</li>
    <li>water</li>
    <li>cloud</li>
    <li>bear</li>
    <li>wolf</li>
</ul>

<div id="output">
    ...
</div>

</body>
</html>

这是一个简单的HTML文档。

Pythonlxml迭代标签

在第一个示例中,我们遍历文档的标签。

#!/usr/bin/python

from lxml import html

fname = 'words.html'
tree = html.parse(fname)

for e in tree.iter():
    print(e.tag)

程序列出了所有可用的HTML标签。

from lxml import html

我们导入html模块。

fname = 'words.html'
tree = html.parse(fname)

我们使用parse解析给定文件中的文档。

for e in tree.iter():
    print(e.tag)

我们使用iter遍历元素。

$ ./tags.py
html
head
meta
title
body
ul
li
li
li
li
li
li
div

Pythonlxml根元素

使用getroot检索根元素。

#!/usr/bin/python

from lxml import html
import re

fname = 'words.html'

tree = html.parse(fname)
root = tree.getroot()

print(root.tag)

print('----------------')

print(root.head.tag)
print(root.head.text_content().strip())

print('----------------')

print(root.body.tag)
print(re.sub('\s+', ' ', root.body.text_content()).strip())

在程序中,我们获取了根元素。我们打印head、body标签和它们的文本内容。

tree = html.parse(fname)
root = tree.getroot()

从文档树中,我们使用getroot方法获取根。

print(root.tag)

我们打印根元素的标签名称(html)。

print(root.head.tag)
print(root.head.text_content().strip())

我们打印head标签及其文本内容。

print(root.body.tag)
print(re.sub('\s+', ' ', root.body.text_content()).strip())

同样,我们打印body标签及其文本内容。要删除过多的空格,我们使用正则表达式。

$ ./root.py
html
----------------
head
Words
----------------
body
sky cup water cloud bear wolf ...

Pythonlxml创建文档

lxml模块允许创建HTML文档。

#!/usr/bin/python

from lxml import etree

root = etree.Element('html', lang='en')

head = etree.SubElement(root, 'head')
title = etree.SubElement(head, 'title')
title.text = 'HTML document'
body = etree.SubElement(root, 'body')

p = etree.SubElement(body, 'p')
p.text = 'A simple HTML document'

with open('new.html', 'wb') as f:
    f.write(etree.tostring(root, pretty_print=True))

我们使用etree模块来生成文档。

root = etree.Element('html', lang='en')

我们创建根元素。

head = etree.SubElement(root, 'head')
title = etree.SubElement(head, 'title')

在根元素中,我们创建了两个子元素。

title.text = 'HTML document'

我们通过text属性插入文本。

with open('new.html', 'wb') as f:
    f.write(etree.tostring(root, pretty_print=True))

最后,我们将文档写入文件。

Pythonlxml查找

findall方法用于查找所有指定的元素。

#!/usr/bin/python

from lxml import html

fname = 'words.html'

root = html.parse(fname)
els = root.findall('body/ul/li')

for e in els:
    print(e.text)

程序找到所有li标签并打印它们的内容。

els = root.findall('body/ul/li')

我们使用findall查找所有元素。我们将确切的路径传递给元素。

for e in els:
    print(e.text)

我们遍历标签并打印它们的文本内容。

$ ./find_all.py
sky
cup
water
cloud
bear
wolf

Pythonlxml通过id查找

可以通过get_element_by_id找到一个特定的元素。

#!/usr/bin/python

from lxml import html

fname = 'words.html'

tree = html.parse(fname)
root = tree.getroot()

e = root.get_element_by_id('output')
print(e.tag)
print(e.text.strip())

程序通过id找到div元素并打印标签名称和文本内容。

$ ./find_by_id.py
div
...

Pythonlxml网络抓取

lxml模块可用于网页抓取。

#!/usr/bin/python

import urllib3
import re
from lxml import html

http = urllib3.PoolManager()

url = 'http://webcode.me/countries.html'
resp = http.request('GET', url)

content = resp.data.decode('utf-8')
doc = html.fromstring(content)

els = doc.findall('body/table/tbody/tr')

for e in els[:10]:
    row = e.text_content().strip()
    row2 = re.sub('\s+', ' ', row)
    print(row2)

该程序获取一个包含人口最多国家列表的HTML文档。它打印表格中排名前十的国家/地区。

import urllib3

要获取网页,我们使用urllib3库。

http = urllib3.PoolManager()

url = 'http://webcode.me/countries.html'
resp = http.request('GET', url)

我们生成对资源的GET请求。

content = resp.data.decode('utf-8')
doc = html.fromstring(content)

我们解码内容并解析文档。

els = doc.findall('body/table/tbody/tr')

我们找到所有包含数据的tr标签。

for e in els[:10]:
    row = e.text_content().strip()
    row2 = re.sub('\s+', ' ', row)
    print(row2)

我们遍历行列表并打印前十行。

$ ./scrape.py
1 China 1382050000
2 India 1313210000
3 USA 324666000
4 Indonesia 260581000
5 Brazil 207221000
6 Pakistan 196626000
7 Nigeria 186988000
8 Bangladesh 162099000
9 Russia 146838000
10 Japan 126830000

在本文中,我们使用lxml在Python中处理了XML/HTML数据。

列出所有Python教程。

未经允许不得转载:我爱分享网 » Python lxml

感觉很棒!可以赞赏支持我哟~

赞(0) 打赏