python - 如何解析文件?

标签 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)

我想知道如何解析包含相同字符串的文件。并且位于同一目录中。请告诉我。

最佳答案

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

关于python - 如何解析文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22022183/

相关文章:

python - 如何在 python 中定义一个包含 1000 位数字的十进制类?

python - 使用 lxml 查找与一组标签名称匹配的元素

python - 如何使用lxml获取url

python - 如何使用 django for python 获取正在访问我的网站的 IP 地址

python - 在 Python 中使用 glob 查找具有非连续数字的路径名

python - 为什么 os.fdopen() 忽略 "mode"参数?

python - 检查 python 是否删除文件夹成功,如果成功,则继续

python - 有没有一种更Pythonic的方式来使用lxml访问父元素的子元素

python - Python中列表到字符串转换的时间和空间复杂度

python - 对于组中的每个 ID,只保留组中的第一个值 !=0,将 other 设置为 0