[英]Parse html element with lxml / xpath
Using lxml/python and xpath, I retrieved the value betwen my tags.使用 lxml/python 和 xpath,我检索了我的标签之间的值。 I would like to get the html properties too, not just the text, my programme works, but skipped two lines.我也想获得 html 属性,而不仅仅是文本,我的程序有效,但跳过了两行。
python : Python :
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import lxml.html
htmltree = lxml.html.parse('data.html')
res = htmltree.xpath("//table[@class='mainTable']/tr/td/text()")
print '\n'.join(res).encode("latin-1")
data.html sample data.html 示例
<table class='mainTable'>
<TR>
<TD bgcolor="#cccccc">235</TD>
<TD bgcolor="#cccccc"> Windows XP / Office 2003.</TD>
<TD bgcolor="#cccccc">
G:\REMI\projets\Migration_XP_Office2003\Procedures\Installation Win XP et Office 2003.doc</TD>
<TD bgcolor="#cccccc">2005-10-18</TD>
<TD bgcolor="#cccccc">2010-12-30</TD></TR>
<TD bgcolor="#cccccc">
<P class="MsoBodyText"
style="margin: 0cm 0cm 0pt;"><STRONG><FONT face="Times New Roman" size="5">blablablablablablbala<BR><BR></FONT></STRONG></FONT></P>
</TD>
<TR>
<TD bgcolor="#cccccc">23</TD>
<TD bgcolor="#cccccc">XEROX/ MAC</TD>
<TD bgcolor="#cccccc">
<P>joint.</P>
<P> </P></TD>
<TD bgcolor="#cccccc">G:\DDTH_INF\REMI\bdcfiles\I098_Page_de_garde_MAC.doc</TD>
<TD bgcolor="#cccccc">2012-12-19</TD>
<TD bgcolor="#cccccc">2012-12-19</TD>
</TR>
</table>
return :返回 :
235 Windows XP / Office 2003.
G:\REMI\projets\Migration_XP_Office2003\Procedures\Installation Win XP
et Office 2003.doc 2005-10-18 2010-12-30
23 XEROX/ MAC G:\DDTH_INF\REMI\bdcfiles\I098_Page_de_garde_MAC.doc
2012-12-19 2012-12-19
I dont understand why the programm skipped我不明白为什么程序跳过
<P class="MsoBodyText"
style="margin: 0cm 0cm 0pt;"><STRONG><FONT face="Times New Roman" size="5">blablablablablablbala<BR><BR></FONT></STRONG></FONT></P>
and和
<P>joint.</P>
<P> </P>
Because it's between <p>
tag ?因为它在<p>
标签之间? I just want to get all the data between each TD.我只想获取每个TD之间的所有数据。 I tried with /tr/td/p/ too but it's not the solution.我也尝试过 /tr/td/p/ 但这不是解决方案。
note: this code is a sample, its possible that html is broken, but my file is well structured.注意:此代码是一个示例,html 可能已损坏,但我的文件结构良好。
This is because you are getting the text()
out of each td
element - which basically means - give me a text node located directly inside the td
element .这是因为您要从每个td
元素中获取text()
- 这基本上意味着 -给我一个直接位于td
元素内的文本节点。
Instead, call .text_content()
on every td
found:相反,在找到的每个td
上调用.text_content()
:
texts = [td.text_content() for td in htmltree.xpath("//table[@class='mainTable']/tr/td")]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.