我有以下 HTML 代码:-
<table class="results">
<tr>
<td>
<a href="..">link</a><span>2nd Mar 2011</span><br>XYZ Consultancy Ltd<br>
<div>....</div>
</td>
</tr>
</table>
我正在使用 lxml+python 代码来解析上面的 HTML 文件。我想检索“XYZ Consultancy Ltd”,但我不知道如何执行此操作。到目前为止我的代码如下:-
import lxml.html
for el in root.cssselect("table.results"):
for el2 in el: #tr tags
for e13 in el2:#td tags
for e14 in e13:
if ( e14.tag == 'a') :
print "keyword: ",e14.text_content()
if (e14.tag == 'span'):
print "date: ",e14.text_content()
最佳答案
您可以使用 CSS 选择器 +
,一个direct adjacent combinator ,获取 <br>
置于正文之前。然后,目标文本包含在其 tail
中。属性。
import lxml.html
root = lxml.html.fromstring('''
<table class="results">
<tr>
<td>
<a href="..">link</a><span>2nd Mar 2011</span><br>XYZ Consultancy Ltd<br>
<div>....</div>
</td>
</tr>
</table>
''')
for br_with_tail in root.cssselect('table.results > tr > td > a + span + br'):
print br_with_tail.tail
# => XYZ Consultancy Ltd
关于python - 使用lxml代码解析HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5646032/