如何用Python lxml获取HTML元素
我有这段HTML代码:
<table>
<tr>
<td class="test"><b><a href="">aaa</a></b></td>
<td class="test">bbb</td>
<td class="test">ccc</td>
<td class="test"><small>ddd</small></td>
</tr>
<tr>
<td class="test"><b><a href="">eee</a></b></td>
<td class="test">fff</td>
<td class="test">ggg</td>
<td class="test"><small>hhh</small></td>
</tr>
</table>
我用这段Python代码来提取所有带有 <td class="test">
的内容,使用的是lxml模块。
import urllib2
import lxml.html
code = urllib.urlopen("http://www.example.com/page.html").read()
html = lxml.html.fromstring(code)
result = html.xpath('//td[@class="test"][position() = 1 or position() = 4]')
效果很好!结果是:
<td class="test"><b><a href="">aaa</a></b></td>
<td class="test"><small>ddd</small></td>
<td class="test"><b><a href="">eee</a></b></td>
<td class="test"><small>hhh</small></td>
(也就是每个 <tr>
的第一列和第四列)现在,我需要提取:
aaa(链接的标题)
ddd(
<small>
标签之间的文本)eee(链接的标题)
hhh(
<small>
标签之间的文本)
我该如何提取这些值呢?
(问题是我需要去掉 <b>
标签,获取第一列的链接标题,并且去掉第四列的 <small>
标签)
谢谢!
2 个回答
4
你为什么不在每一步中只获取你想要的东西呢?
links = [el.text for el in html.xpath('//td[@class="test"][position() = 1]/b/a')]
smalls = [el.text for el in html.xpath('//td[@class="test"][position() = 4]/small')]
print zip(links, smalls)
# => [('aaa', 'ddd'), ('eee', 'hhh')]
8
如果你使用 el.text_content()
,那么你会把每个元素中的所有标签内容都去掉,也就是说:
result = [el.text_content() for el in result]