如何解析文件?

时间:2014-02-25 17:51:49

标签: python python-3.x lxml lxml.html

以下代码解析字符串。

import lxml.html

doc = lxml.html.document_fromstring("""<html>
 <body>
   <span class="simple_text">One</span> tehfghhxt</br>
   <span class="cyrillic_text">Второй</span> cyrcyrcyr</br>
 </body>
</html>
""")

txt1 = doc.xpath('/html/body/span[@class="simple_text"]/text()[1]')
print(txt1)

我想知道如何解析包含相同字符串的文件。和它在同一目录中。请告诉我。

1 个答案:

答案 0 :(得分:2)

string = open('file_with_string.html', 'r').read()
doc = lxml.html.document_fromstring(string)