gpt4 book ai didi

python - 如何使用 python lxml 获取 html 元素

转载 作者:数据小太阳 更新时间:2023-10-29 02:00:40 24 4
gpt4 key购买 nike

我有这个 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 (the title of the link)

ddd (text between <small> tag)

eee (the title of the link)

hhh (text between <small> tag)

我如何提取这些值?

(问题是我必须删除 <b> 标签并在第一列中获取 anchor 的标题并删除第四列中的 <small> 标签)

谢谢!

最佳答案

如果您执行 el.text_content(),您将从每个元素中删除所有标签内容,即:

result = [el.text_content() for el in result]

关于python - 如何使用 python lxml 获取 html 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2807209/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com