1 から lxmlのインポートetree 2 =テキスト" の<div> <P> nmsl </ P> <スパン> nmsl </スパン> </ div> " 3 DEF htmlstree(テキスト): 4 HTML = etree.HTML(テキスト) 5 結果= etree.tostring(HTML) 6 プリント(結果) 7 戻り result.decode(' UTF-8 ' ) 8 #解析HTML字符串并且会为标签自动加上<HTML> <BODY> </ BODY> </ HTML> 9 DEF parseetree(): 10 パーサー= etree.HTMLParser(エンコード= 'UTF-8 ") 。11 HTML etree.parse =(" index111.html "、=パーサパーサ) 12である 結果=(HTML、エンコーディング= etree.tostring ' UTF-8 ').decode(" UTF-を8 " ) 13で 印刷(結果) 14 #HTMLパーサを指定するように書き込み障害がこのような従来の<BR/> XMLパーサなどによって間違ったHTMLタグであろうので、解析XML 15 IF __name__ == 「__main__ 」: 16 parseetree()を
上記はetreeの使用例であります
HTML文字列htmlファイルを解決します
lxmlのインポートetree デフparseetree(): パーサ = etree.HTMLParser(エンコード= ' UTF-8 ' ) HTML = etree.parse(" index111.html "、パーサ= パーサ) TRS = html.xpath(" // [@onclick] [ID @] " ) のための TR でTRS。 結果は、 =(TR、エンコーディング= etree.tostring ' UTF-8 ').decode(" UTF-8 " ) 、印刷(結果) DEF )(parseetree1。 パーサ = etree.HTMLParser(エンコード= ' UTF-8 ' ) HTML = etree.parse(" index111.html "、パーサ= パーサ) TR = html.xpath(" // [@onclick] [ID @] ")[3 ] 結果 = etree.tostring(TR、コード= ' UTF-8 ').decode(" UTF-8 " ) 、印刷(結果) 場合 __name__ == " __main__ " : parseetree() 印刷(" *************** " ) parseetree1()
上記は、解析のhtmlへの使用のXPathであります
以下がその結果です
添付:https://www.w3school.com.cn/xpath/xpath_syntax.asp XPathの構文