1、從文件中讀取html內容,然后xpath加載?
with open('FilePath', 'r',encoding='utf8') as file:html = file.read()
tree = etree.HTML(html)
2、基本定位語法
/?? ?從根節點開始選取?? ?/html/div/span
//?? ?從任意節點開始選取?? ?//input
.?? ?選取當前節點?? ??
..?? ?選取當前節點的父節點? ?
3、正則表達式匹配內容
? CitedNames = item.xpath('.//a[re:test(text(),"[^View All]")]/text()',namespaces={"re": "http://exslt.org/regular-expressions"})
其中[^View All]是正則表達式部分,這里是text不等于View All的;需要注意的是,如果是等于,則不需要[],即直接用,如:
skill = tree.xpath('//div[@class="nova-c-card__body nova-c-card__body--spacing-inherit"]//b[re:test(text(),"Skills and Expertise")]/text()',namespaces={"re": "http://exslt.org/regular-expressions"})
xpath中的.是當前節點開始;item是我當前要處理的節點。
說明:這里我使用的是re:test,因為re:test比re:match更高效,因為test返回的是一個布爾值,而match返回的是滿足條件的數組,隨意根據自己的需求調整。
不包括的寫法:not(contains(xx,"具體內容"),如:
#text中不包括[...]的
resInfo['authors'] = researchItem[3].xpath('.//span[not(contains(text(),"[...]"))]/text()')
#如果是屬性中不包括的則,如,a中href不包含more的
resInfo['authors'] = researchItem[3].xpath('.//a[not(contains(@href,"more"))]/text()')
4、當前節點的父節點的父節點
..為當前節點的父節點的選擇,父節點的父節點即是../../;如:
skill[0].xpath('../..//a[re:test(text(),"[^Show more]")]/text()',namespaces={"re": "http://exslt.org/regular-expressions"})
5、根據id或class檢索
#從根節點開始找id為xxx的div
researchItemDiv = tree.xpath('//div[@id="research-items"]')#從根節點出發找class為xxx的div內的文本
aboutArr = tree.xpath('//div[@class="nova-c-card__body nova-c-card__body--spacing-inherit"]//text()')