我需要编写xpath来查找仅包含1th和1 td的表中的行的帮助
范例html
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<table>
<tr>
<th>test</th>
<td>abc</td>
</tr>
<tr>
<th>test1</th>
<td>abc</td>
<td>abc</td>
</tr>
<th>test2</th>
<td>abc</td>
</table>
</body>
</html>
对于此html,我希望仅第一行和最后一行,如果该行包含th和td以外的任何内容,则应跳过该行
'//table/tr[th and td]'
我到达了这个xpath,但是td
如果行包含其他<a
或任何内容,这将包括重复不过滤
这是可行的-不是很优雅,但是可以。我扩展了示例HTML,以引入更多有问题的节点:
test = """
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<table>
<tr>
<th>test</th>
<td>abc</td>
</tr>
<tr>
<th>test1</th>
<td>abc</td>
<td>abc</td>
</tr>
<tr>
<th>test2</th>
<td>abc</td>
</tr>
<tr>
<a>test3</a>
<td>abcd</td>
</tr>
<tr>
<td>test4</td>
<td>abcd</td>
</tr>
</table>
</body> """
import lxml.html
doc = lxml.html.fromstring(test)
good_tags = ['th','td']
targs = doc.xpath('//tr')
for targ in targs:
tr = targ.xpath('.//*')
if len(tr)==2 and (tr[0].tag != tr[1].tag) and tr[0].tag in good_tags and tr[1].tag in good_tags:
print(lxml.html.tostring(targ).decode())
输出:
<tr>
<th>test</th>
<td>abc</td>
</tr>
<tr>
<th>test2</th>
<td>abc</td>
</tr>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句