下面是我正在使用的一个简单的 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>
line
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')
and 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)
Output:
<td>Name</td>
<td>Comments</td>
<td>Melodie</td>
<td>Machaela</td>
<td>Rhoan</td>
顺便说一句,与 html.parser 相比,我更喜欢 lxml。它对格式错误的 HTML 更快、更稳健。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)