html_doc = ''' <html> <head> <title> The Dormouse's story </title> </head> <body> <p class="title"> <b> The Dormouse's story </b> </p> <p class="story"> Once upon a time there were three little sisters; and their names were <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a> <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a> and <a class="sister" href="http://example.com/tillie" id="link2">Tillie</a> and they lived at the bottom of a well. </p> <p class="story"> 測試中文 </p> <ul> <li> python </li> <li> C# </li> <li> java </li> <li> .net </li> </ul> </body> </html> ''' from lxml import etree ''' from 解析正文 import html_doc 導入解析內容即(html) from lxml import etree 使用Xpath 所依賴的包 ''' # print(html_doc) etr = etree.HTML(html_doc) #創建解析對象 html 對象 a_like=etr.xpath('//p[@class="story"]/a[starts-with(@href,"http://example.com/")]/@href') a_text=etr.xpath('//p[@class="story"]/a[starts-with(@href,"http://example.com/")]/text()') ''' 詳細解析: // 直接定位到 class 等於 story 的p 標籤 / 定位到 a 標籤 並且 a 標籤的href 屬性 要以"http://example.com/" 開頭 starts-with 可以用於其它地方 比如 p[starts-with(@class,"s")] 意思就是 尋找 p 標籤的class 是s 的元素 ''' t_l=zip(a_text,a_like) link_text={} for l,t in t_l: link_text.update({l:t}) print(link_text) print(link_text.get('Elsie','沒有'))
xpath 使用方法(starts-with) 匹配頭
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.