xpath的使用:定位,获取文本和属性值
admin
2023-07-19 00:02:24
0

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

相关内容

热门资讯

以色列袭击黎巴嫩,特朗普急了 当地时间6月14日,美国总统特朗普在个人社交媒体发文,回应以色列袭击黎巴嫩。特朗普表示,贝鲁特袭击本...
被指“云林最近有点乱”,柯文哲... 海峡导报综合报道 台湾民众党创党主席柯文哲偕党主席黄国昌14日下午到云林县斗六市与党员志工座谈,台媒...
赖瑞隆为何攻击柯志恩家人?蓝营... 海峡导报综合报道 民进党高雄市长参选人赖瑞隆质疑国民党高雄市长参选人柯志恩家人资产在美国,柯14日痛...
世界杯看台对900万粉韩博主做... 因在美加墨世界杯赛场看台上对一名韩国博主做出疑似“眯眯眼”的种族歧视动作,墨西哥哈利斯科州测量师与地...
伊朗队在墨西哥的临时大本营:谢... 在墨西哥卡连特体育场(Estadio Caliente)外围的道路上,敞篷巡逻车往来穿梭。车上坐着戴...
伊朗称将就贝鲁特遭袭报复以色列 针对以色列今天(6月14日)再次袭击黎巴嫩首都贝鲁特南郊,伊朗武装部队哈塔姆·安比亚中央司令部副司令...
前脚清查后脚增产,违规电池厂称... 《财经调查》栏目不断接到消费者反映,一些商家为了吸引消费者,谋一己私利,被总台3·15晚会曝光整顿后...
足球成了“人质”?世界杯补水背... 澎湃新闻记者 朱轶世界杯开赛不过3天,关于补水暂停插入电视广告的争议,迅速席卷整个足坛。“足球已经沦...
8死2失踪渔船倾覆事故调查报告... 辽宁省应急管理厅6月14日公布辽宁葫芦岛辽绥渔35261船“10·18”重大倾覆事故调查报告。调查认...
28岁男子去世留40万房贷,银... 近日,岳阳一指定遗产管理人案引发关注:28岁的男子小王(化姓)不幸去世时,其生前49万的房贷未还完。...