html = etree.HTML(str/bytes)
参数可以是str或bytes类型,返回值是etree._Element。
调用etree.parse('hello.html'),参数是文件路径,返回值是etree._ElementTree。
etree.tostring(html,encoding='unicode')
不加编码,返回bytes,加了返回str。
etree.parse()读取文件之后用xpath不成功。<html xmlns="http://www.w3.org/1999/xhtml">把xmlns属性去掉就可以。
但是用文件以二进制打开,etree.HTML再用xpath就可以。
……
用文本文件打开,再用etree.HTML就不行。
Traceback (most recent call last): File "d:我的文档py est iebaqu.py", line 53, in <module> html=etree.HTML(html2) File "srclxmletree.pyx", line 3178, in lxml.etree.HTML (srclxmletree.c:80497) File "srclxmlparser.pxi", line 1866, in lxml.etree._parseMemoryDocument (srclxmletree.c:121177) ValueError: Unicode strings with encoding declaration are not supported. Please use bytes input or XML fragments without declaration.
看不懂。以后就用bytes操作了。谁特么知道文本怎么解析的。
etree.parse() 返回 lxml.etree._ElementTree 类型
etree.HTML() 返回 lxml.etree._Element 类型
xpath
'/root/elem'
第一个'/'表示从根节点开始匹配,第二个表示提取子元素
//提取表示所有后代元素
xpath返回list,即使加了[1],[last()],也一样。
@class 选取class属性
@class="i" 选取值为i的class属性
list[idx].text 获取元素内容
from lxml.html.clean import Cleaner
删除标签,保留内容
etree.Element('html') 创建元素
html.append(elem) 追加在后面
ref: