调用:
from lxml import etree
解析网页代码:
html = etree.HTML(ret)
网页源码修补:
etree.tostring(html)
文本获取:
html.xpath('//<节点名称>/text()')
节点获取:
所有节点获取:
html.xpath('//*')
指定节点获取:
html.xpath('//<节点名称>')
html.xpath('//<节点名称>[1]') #从一开始
指定子节点获取:
html.xpath('//<节点名称>/<子节点名称>')
指定孙子节点获取:
html.xpath('//<节点名称>//<孙子节点名称>')
选取父亲节点:
html.xpath('//<节点名称>/..')
属性匹配节点获取:
html.xpath('//<节点名称>[@xxx=xx]')
多属性匹配节点获取:
html.xpath('//<节点名称>[contains(@xx,xx)and @xx=xx]')
按顺序选择节点:
html.xpath('//li[1]') #第一个li节点
html.xpath('//li[last()]') #最后一个li节点
html.xpath('//li[post()<3]') #第一二li节点
html.xpath('//li[last()-2]') #倒数第三个li节点
节点轴:
html.xpath('//li/ancestor::*') #li的所有祖先节点
html.xpath('//li/attribute::*') #li的所有属性
html.xpath('//li/child::*') #li的所有直接儿子节点
html.xpath('//li/descendant::*') #li的所有子孙节点
html.xpath('//li[1]/following::*') #li节点后的所有节点
html.xpath('//li[1]/following_sibling::*') #li的所有同级节点