html的结构如下:
<div class="my_class">
<div>important text</div>
<div class="my_class">
<div>not important</div>
</div>
</div>
<div class="my_class">
<div>important text</div>
<div class="my_class">
<div>not important</div>
</div>
</div>
...
基本上,有许多div与它们的子div同名,最终,我想找到partent div下的“重要文本”。你知道吗
当我试图用^{cl1}查找所有div时$
下面是获取class=“my\u class”的所有div并查找重要文本的代码:
my_div_list = soup.find_all('div', attrs={'class': 'my_class'})
for my_div in my_div_list:
text_item = my_div.find('div') # to get to the div that contains the important text
print(text_item.getText())
显然,输出是:
important text
not important
important text
not important
...
当我需要的时候:
important text
important text
...
对于bs4.7.1,您可以使用:has和:first child
您可以迭代
soup.contents
:输出:
从
findall()
文档中:因此,假设div的第一级位于标记
<head>
和<body>
下,您可以设置输出: 你知道吗
相关问题 更多 >
编程相关推荐