gpt4 book ai didi

python - 如何在 Beautifulsoup 的 find_all() 函数中过滤没有属性的标签?

转载 作者:行者123 更新时间:2023-12-02 01:42:38 26 4
gpt4 key购买 nike

下面是我正在使用的一个简单的 html 源代码

<html>
<head>
<title>Welcome to the comments assignment from www.py4e.com</title>
</head>
<body>
<h1>This file contains the actual data for your assignment - good luck!</h1>

<table border="2">
<tr>
<td>Name</td><td>Comments</td>
</tr>
<tr><td>Melodie</td><td><span class="comments">100</span></td></tr>
<tr><td>Machaela</td><td><span class="comments">100</span></td></tr>
<tr><td>Rhoan</td><td><span class="comments">99</span></td></tr>

下面是我尝试获取 <td>Melodie</td> 的代码行

html='html text file aboved'

soup=BeautifulSoup(html,'html.parser')

for tag in soup.find_all('td'):
print(tag)
print('----') #Result:
#===============================================================================
# <td>Name</td>
# ----
# <td>Comments</td>
# ----
# <td>Melodie</td>
# ----
# <td><span class="comments">100</span></td>
# ----
# <td>Machaela</td>
# ----
# <td><span class="comments">100</span></td>
# ----
# <td>Rhoan</td>
# ----
#.........
#===============================================================================

现在我想得到 <td>name<td>仅行而不是带有“span”和“class”的行。我尝试了 2 个过滤器 soup.find_all('td' and not 'span')soup.find_all('td', attrs={'class':None})但这些都不起作用。我知道还有其他方法,但我想在 soup.find_all() 中使用过滤器。我的预期输出(实际上我的最终目标是获得两个 <td> 之间的人名):

# <td>Name</td>
# ----
# <td>Comments</td>
# ----
# <td>Melodie</td>
# ----
# <td>Machaela</td>
# ----
# <td>Rhoan</td>
# ----

最佳答案

您可以通过两个单独的选择器调用获得所需的输出:

from bs4 import BeautifulSoup

html = """
<body>
<table border="2">
<tr>
<td>Name</td><td>Comments</td>
</tr>
<tr><td>Melodie</td><td><span class="comments">100</span></td></tr>
<tr><td>Machaela</td><td><span class="comments">100</span></td></tr>
<tr><td>Rhoan</td><td><span class="comments">99</span></td></tr>
"""
soup = BeautifulSoup(html, "lxml")

for elem in soup.select("td"):
if not elem.select(".comments"):
print(elem)

输出:

<td>Name</td>
<td>Comments</td>
<td>Melodie</td>
<td>Machaela</td>
<td>Rhoan</td>

顺便说一句,比起 html.parser,更喜欢 lxml。它对格式错误的 HTML 更快、更健壮。

关于python - 如何在 Beautifulsoup 的 find_all() 函数中过滤没有属性的标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71401198/

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