ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

使用 lxml 中的 xpath 高效提取文本与标签属性值

2021-11-30 13:00:46  阅读:202  来源: 互联网

标签:xpath lxml 标签 去往 html div 文本 属性


转自:使用 lxml 中的 xpath 高效提取文本与标签属性值

# 我们爬取网页的目的,无非是先定位到DOM树的节点,然后取其文本或属性值

myPage = '''<html>
        <title>TITLE</title>
        <body>
        <h1>我的博客</h1>
        <div>我的文章</div>
        <div id="photos">
         <img src="pic1.jpeg"/><span id="pic1">PIC1 is beautiful!</span>
         <img src="pic2.jpeg"/><span id="pic2">PIC2 is beautiful!</span>
         <p><a href="http://www.example.com/more_pic.html">更多美图</a></p>
         <a href="http://www.baidu.com">去往百度</a>
         <a href="http://www.163.com">去往网易</a>
         <a href="http://www.sohu.com">去往搜狐</a>
        </div>
        <p class="myclassname">Hello,\nworld!<br/>-- by Adam</p>
        <div class="foot">放在尾部的其他一些说明</div>
        </body>
        </html>'''
        
html = etree.fromstring(myPage)

# 一、定位
divs1 = html.xpath('//div')
divs2 = html.xpath('//div[@id]')
divs3 = html.xpath('//div[@class="foot"]')
divs4 = html.xpath('//div[@*]')
divs5 = html.xpath('//div[1]')
divs6 = html.xpath('//div[last()-1]')
divs7 = html.xpath('//div[position()<3]')
divs8 = html.xpath('//div|//h1')
divs9 = html.xpath('//div[not(@*)]')

# 二、取文本 text() 区别 html.xpath('string()')
text1 = html.xpath('//div/text()')
text2 = html.xpath('//div[@id]/text()')
text3 = html.xpath('//div[@class="foot"]/text()')
text4 = html.xpath('//div[@*]/text()')
text5 = html.xpath('//div[1]/text()')
text6 = html.xpath('//div[last()-1]/text()')
text7 = html.xpath('//div[position()<3]/text()')
text8 = html.xpath('//div/text()|//h1/text()')


# 三、取属性 @
value1 = html.xpath('//a/@href')
value2 = html.xpath('//img/@src')
value3 = html.xpath('//div[2]/span/@id')


# 四、定位(进阶)
# 1.文档(DOM)元素(Element)的find,findall方法
divs = html.xpath('//div[position()<3]')
for div in divs:
    ass = div.findall('a')  # 这里只能找到:div->a, 找不到:div->p->a
    for a in ass:
        if a is not None:
            #print(dir(a))
            print(a.text, a.attrib.get('href')) #文档(DOM)元素(Element)的属性:text, attrib

# 2.与1等价
a_href = html.xpath('//div[position()<3]/a/@href')
print(a_href)

# 3.注意与1、2的区别
a_href = html.xpath('//div[position()<3]//a/@href')
print(a_href)

  

标签:xpath,lxml,标签,去往,html,div,文本,属性
来源: https://www.cnblogs.com/iupoint/p/15623709.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有