我在使用 next_sibling
时遇到了困难(与 next_element
类似)。如果用作属性,我不会得到任何返回,但如果用作 find_next_sibling
(或 find_next
),则它可以工作。
来自 doc :
find_next_sibling
:“迭代树中元素的其余同级元素。[...]返回(匹配的)第一个元素”find_next
:“这些方法使用 .next_elements 迭代 [...] 并返回第一个”
因此,find_next_sibling
取决于 next_siblings
。 next_sibling
依赖于什么以及为什么它们不返回任何内容?
from bs4 import BeautifulSoup
html = """
<div class="......>
<div class="one-ad-desc">
<div class="one-ad-title">
<a class="one-ad-link" href="www this is the URL!">
<h5>
Text needed
</h5>
</a>
</div>
<div class="one-ad-desc">
...and some more needed text here!
</div>
</div>
</div>
"""
soup = BeautifulSoup(html, 'lxml')
for div in soup.find_all('div', class_="one-ad-title"):
print('-> ', div.next_element)
print('-> ', div.next_sibling)
print('-> ', div.find_next_sibling())-> ')
break
输出
->
->
-> <div class="one-ad-desc">
...and some more needed text here!
</div>
最佳答案
我认为这里的要点是 .find_next_sibling()
范围位于树上的下一级。
而 .next_element
和 .next_sibling
范围位于解析树的同一级别。
所以看一下并打印元素的名称,您将看到下一个元素不是标签,因为树的同一级别上没有任何内容:
for div in soup.find_all('div', class_="one-ad-title"):
print('-> ', div.next_element.name)
print('-> ', div.next_sibling.name)
print('-> ', div.find_next_sibling().name)
#output
-> None
-> None
-> div
因此,如果您将输入更改为一行,并且标签之间没有空格,...,您将得到以下结果:
from bs4 import BeautifulSoup
html = """
<div class="......><div class="one-ad-desc"><div class="one-ad-title"><a class="one-ad-link" href="www this is the URL!"><h5>Text needed</h5></a></div><div class="one-ad-desc">...and some more needed text here!</div></div></div>"""
soup = BeautifulSoup(html, 'lxml')
for div in soup.find_all('div', class_="one-ad-title"):
print('-> ', div.next_element)
print('-> ', div.next_sibling)
print('-> ', div.find_next_sibling())
输出:
-> <a class="one-ad-link" href="www this is the URL!"><h5>Text needed</h5></a>
-> <div class="one-ad-desc">...and some more needed text here!</div>
-> <div class="one-ad-desc">...and some more needed text here!</div>
注意 “需要文本”不在您所选标签的同级标签中,而是在其子标签之一中。选择“需要文本” -> print('-> ', div.find_next().text)
关于python - bs4 `next_sibling` VS `find_next_sibling`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71616816/