python - bs4 `next_sibling` VS `find_next_sibling`

标签 python python-3.x web-scraping beautifulsoup

我在使用 next_sibling 时遇到了困难(与 next_element 类似)。如果用作属性,我不会得到任何返回,但如果用作 find_next_sibling (或 find_next),则它可以工作。 来自 doc :

  • find_next_sibling:“迭代树中元素的其余同级元素。[...]返回(匹配的)第一个元素”
  • find_next:“这些方法使用 .next_elements 迭代 [...] 并返回第一个”

因此,find_next_sibling 取决于 next_siblingsnext_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/

相关文章:

performance - Python列表追加和扩展 - 速度慢

javascript - 在 Javascript 和 Python 中为不同的数据类型分配了多少内存?

Stack Overflow 中从下一页到 scrapy 的 Xpath

javascript - Selenium 找到的元素缺少一些属性

python - 为 df1 中的每个项目查找 df2 中最接近的项目

python - 在 sqlalchemy 中外部连接两个表时按问题排序

python - Python 中的 MySQL 连接器

python: pandas: 过滤一列并获取另一列的平均值

python - Starmap 在传入参数之前修改参数?

javascript - 如何下载在 puppeteer 的新选项卡中打开的 pdf?