gpt4 book ai didi

python - 如何使用 lxml 和 python 从表中查找特定的 xpath td 类

转载 作者:太空宇宙 更新时间:2023-11-04 10:22:32 25 4
gpt4 key购买 nike

我正在尝试使用 Python lxml 从页面导入文本列表。这是我目前所拥有的。

test_page.html 来源:

<html>
<head>
<title>Test</title>
</head>
<body>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr><td><a title="This page is cool" class="producttitlelink" href="about:mozilla">This page is cool</a></td></tr>
<tr height="10"></tr>
<tr><td class="plaintext">This is a really cool description for my really cool page.</td></tr>

<tr><td class="plaintext">Published: 7/15/15</td></tr>

<tr><td class="plaintext">



</td></tr>
<tr><td class="plaintext">


</td></tr>
<tr><td class="plaintext">


</td></tr>
<tr><td class="plaintext">

</td></tr>


</tbody>
</table>
</body>

Python代码:

from lxml import html
import requests
page = requests.get('http://127.0.0.1/test_page.html')
tree = html.fromstring(page.text)
description = tree.xpath('//table//td[@class="plaintext"]/text()')
>> print (description)
['This is a really cool description for my really cool page.', 'Published: 7/15/15', '\n\t\t\n\t\t\t\t\n\t\t\n\t', '\n\t\t\t\t\n\t\n\t', '\n\t\t\t\t\n\t\n\t', '\n\t\t\t\t\n\t']
>>

然而,期望的最终结果是:

['This is a really cool description for my really cool page. Published: 7/15/15']

我以为使用 [1] -

tree.xpath('//table//td[@class="plaintext"][1]/text()') 

可能让我收到第一行:

['This is a really cool description for my really cool page.'] 

但是它会拉取整个列表。

有没有办法只使用此 html 的 xpath 来指定单行或行列表?

最佳答案

你可以这样试试:

from lxml import html

source = """html posted in the question here"""
tree = html.fromstring(source)
tds = tree.xpath('//table//td[@class="plaintext"]/text()[normalize-space()]')
description = ' '.join(tds)
print(description)

应用于 text() 的 XPath 谓词[normalize-space()] 将仅返回那些非空白文本节点。

使用有问题的 HTML,上述代码的输出完全符合要求:

This is a really cool description for my really cool page. Published: 7/15/15

关于python - 如何使用 lxml 和 python 从表中查找特定的 xpath td 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31455157/

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