爬虫基础--lxml库和Xpath语法

本文介绍了Python中强大的lxml库,详细探讨了XPath语言的基础和使用技巧,包括如何通过XPath选择元素、提取数据,以及在爬虫项目中应用XPath解析网页内容的方法。
摘要由CSDN通过智能技术生成
from lxml import etree

"""
1.读取html字符串
"""
text = \
"""
<tr class="hots">
    <td class="1">hot1</td>
    <td class="2">hot2</td>
    <td class="3">hot3</td>
    <td class="4">hot4</td>
    <td class="5">hot5
    <td class="6">爬虫
</tr>
"""
#利用了etree.HTML,将字符串解析为HTML文档【能帮助我们进行标签补全】
html = etree.HTML(text)
print(type(html))
#打印解析后的htmL页面[解析后的文档是一个bytes流数据],要先编码再解码
result = etree.tostring(html,encoding='utf8').decode('utf8')
print(result)


"""
2.直接解析html文件
【默认使用xml解析器】
"""
#自定义一个HTML解析器
parser = etree.HTMLParser(encoding='utf8')

html = etree.parse(r"/Users/dx/Desktop/(凡博)Python爬虫资料/3.Python爬虫数据提取-Xpath语法/课程资料/test.html",parser=parser)
result = etree.tostring(html,encoding='utf8').decode('utf8')
print(result)
text = \
"""
<ul class="ullist" padding="1" spacing="1">
    <li>
        <div id="top">
            <span class="position" width="350">职位名称</span>
  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值