Python网络爬虫案例实战:解析网页:Ixml解析网页

Python网络爬虫案例实战:解析网页:Ixml解析网页

lxml是一个HTML/XML的解析器,主要的功能是如何解析和提取HTML/XML数据。1xml和正则表达式一样,也是用C实现的,是一款高性能的Python HTML/XML解析器,可以利用之前学习的XPath语法,来快速定位特定元素以及节点信息。
安装lxml也非常简单,直接使用pip安装,代码为:

pip install lxml

5.5.1使用lxml

使用lxml爬取网页源代码数据也有3种方法,即XPath选择器、CSS 选择器和Beautiful Soup的find()方法。与利用 Beautiful Soup 相比,lxml还多了一种XPath选择器方法。
下面利用1xml来解析HTML 代码:

from lxml import etree

# 定义修正后的 HTML 字符串
html = '''
<html>
<head>
<meta name="content-type" content="text/html; charset=utf-8"/>
<title>友情链接查询一站长工具</title>
<!--uRj0Ak8VLEPhjWhg3m9z4EjXJwc-->
<meta name="Keywords" content="友情链接查询"/>
<meta name="Description" content="友情链接查询"/>
</head>
<body>
<h1 class="heading">Top News</h1>
<p style="font-size:200%">World News only on this page</p>
Ah, and here's some more text, by the way.
<p>... and this is a parsed fragment...</p>
<a href="http://www.cydf.org.cn/" rel="nofollow" target="_blank">青少年发展基金会</a>
<a href="http://www.4399.com/flash/32979.htm" target="_blank">洛克王国</a>
<a href="http://www.4399.com/flash/35538.htm" target="_blank">奥拉星</a>
<a href="http://game.3533.com/game/" target="_blank">手机游戏</a>
<a href="http://game.3533.com/tupian/" target="_blank">手机壁纸</a>
<a href="http://www.4399.com/" target="_blank">4399 小游戏</a>
<a href="http://www.91wan.com/" target="_blank">91wan 游戏</a>
</body>
</html>
'''

# 解析 HTML 内容
page = etree.HTML(html)

# 使用 XPath 查找所有 <a> 元素
hrefs = page.xpath("//a")

# 打印每个 <a> 元素的属性
for href in hrefs:
    print(href.attrib)

输出:

{
   'href': 'http://www.cydf.org.cn/', 'rel': 'nofollow', 'target': '_blank'}
{
   'href': 'http://www.4399.com/flash/32979.htm', 'target': '_blank'}
{
   'href': 'http://www.4399.com/flash/35538.htm', 'target': '_blank'}
{
   'href': 'http://game.3533.com/game/', 'target': '_blank'}
{
   'href': 'http://game.3533.com/tupian/', 'target': '_blank'}
{
   'href': 'http://www.4399.com/', 'target': '_blank'}
{
   'href': 'http://www.91wan.com/', 'target': '_blank'}

提示:lxml可以自动修正HTML 代码。

5.5.2文件读取

除了直接读取字符串,lxml还支持从文件中读取内容。新建一个hello.HTML文件:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document Title</title>
</head>
<body>
    <div>
        <ul>
            <li class="item-0"
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值