网创优客建站品牌官网
为成都网站建设公司企业提供高品质网站建设
热线:028-86922220
成都专业网站建设公司

定制建站费用3500元

符合中小企业对网站设计、功能常规化式的企业展示型网站建设

成都品牌网站建设

品牌网站建设费用6000元

本套餐主要针对企业品牌型网站、中高端设计、前端互动体验...

成都商城网站建设

商城网站建设费用8000元

商城网站建设因基本功能的需求不同费用上面也有很大的差别...

成都微信网站建设

手机微信网站建站3000元

手机微信网站开发、微信官网、微信商城网站...

建站知识

当前位置:首页 > 建站知识

xpath的使用:定位,获取文本和属性值

myPage = '''
TITLE




Hello,\nworld!
-- by Adam


放在尾部的其他一些说明


'''

站在用户的角度思考问题,与客户深入沟通,找到兴山网站设计与兴山网站推广的解决方案,凭借多年的经验,让设计与互联网技术结合,创造个性化、用户体验好的作品,建站类型包括:成都网站建设、成都网站制作、企业官网、英文网站、手机端网站、网站推广、申请域名、网页空间、企业邮箱。业务覆盖兴山地区。

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|//h2')
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()|//h2/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)

参考:https://www.cnblogs.com/hhh6460/p/5079465.html


当前名称:xpath的使用:定位,获取文本和属性值
地址分享:http://bjjierui.cn/article/ppiice.html

其他资讯