from lxml import etree root = etree.Element('root')
from lxml import etree root = etree.Element('root') span = etree.SubElement(root, 'span')
from lxml import etree root = etree.Element('root') span = etree.SubElement(root, 'span') root.remove(span)
from lxml import etree root = etree.Element('root') root.clear()
from lxml import etree root = etree.Element('root') span = etree.SubElement(root, 'span') # 获取标签数 len(root) # 获取标签索引号,如果有多个相同标签的话,可以区分 root.index(span) # 按位置插入 root.insert(0, etree.Element('p')) # 尾部添加 root.append(etree.Element('strong'))
获取标签父节点的两种方法
from lxml import etree root = etree.Element('root') span = etree.SubElement(root, 'span') # 获取父节点方法一 span.getparent().tag # 获取父节点方法二,用列表获取子节点,再获取父节点 root[0].getparent().tag
from lxml import etree root = etree.Element('root') root.set('title', '这是一个root标签')
获取属性的三种方法
from lxml import etree root = etree.Element('root') # 获取属性方法一 root.get('title') # 获取属性方法二,参考字典的操作 root.keys(),root.values(),root.items() # 获取属性方法三,直接拿到属性存放的字典 root.attrib
添加文本和追加文本
from lxml import etree root = etree.Element('root') # 标签内添加文本 root.text='i am autofelix' # 标签后追加文本 root.tail = 'i am autofelix'
from lxml import etree root = etree.Element('root') word = root.xpath('//text()') word[0].getparent().tag
from lxml import etree root = etree.Element('root') word = root.xpath('//text()') # 是否是text文本 word.is_text # 是否是tail文本 word.is_tail
from lxml import etree html = etree.fromstring('<root>autofelix</root>') html.tag etree.tostring(html)
from lxml import etree html = etree.XML('<root>autofelix</root>') html.tag etree.tostring(html)
from lxml import etree # 去除xml文件里的空行 parser= etree.XMLParser(remove_blank_text=True) root = etree.XML('<root> auto felix </root>', parser) print etree.tostring(root)
HTML方法,如果没有<html>和<body>标签,会自动补上
from lxml import etree html = etree.HTML('<root>autofelix</root>') etree.tostring(html)
from lxml import etree root = etree.XML('<root><a class="uname">i am autofelix<b/><c/><b/></a></root>') # findall操作返回列表 root.findall('a')[0].text # find操作就相当与找到了这个元素节点,返回匹配到的第一个元素 root.find('.//a').text # 配合列表解析 [ b.text for b in root.findall('.//a') ] # 根据属性查询 root.findall('.//a[@class]')[0].tag