Xpath语法

使用//获取整个页面中的元素,然后写标签名,然后用谓词进行提取。如:
//div[@class='abc']

注意:
1./和//的区别: /只获取子节点 , //获取子孙节点
一般//用的较多 视情况而定

2.contains:有时某个属性包含了多个值,那么可以使用contains函数如:
//div[contains(@class,'job_detail')]

3.谓词中的下标是从1开始的 不是从0开始的

4.使用lxml解析HTML代码:
解析html字符串:使用lxml.etree.HTML进行解析,如:
htmlElement = etree.HTML(text)
print(etree.tostring(htmlElement,encoding='utf-8').decode('utf-8'))

解析HTML文件: 使用lxml.etree.parse进行解析
htmlElement = etree.parse("Tencent.html")
print(etree.tostring(htmlElement,encoding='utf-8').decode('utf-8))

这个函数默认的是xml解析器,如果碰到不规范的HTML代码就会解析错误
这时需要自己创建HTML解析器,如:
parser = etree.parserHTML(encoding='utf-8')
htmlElement = etree.parse("Lagou.html")
print(etree.tostring(htmlElement,encoding='utf-8').decode('utf-8))

posted @ 2018-09-11 13:35  欲得周郎顾  阅读(124)  评论(0编辑  收藏  举报