在 Python 爬虫中,使用 BeautifulSoup 获取下一个标签的方法是:导入 BeautifulSoup 库解析 HTML 文档定位当前标签使用 next_sibling 属性获取下一个标签

Python 爬虫中获取下一个标签的方法
在 Python 爬虫中,使用 BeautifulSoup 解析 HTML 时,可以使用 next_sibling 属性获取当前标签的下一个相邻标签。
步骤:
-
导入 BeautifulSoup 库:
立即学习“Python免费学习笔记(深入)”;
<code class="python">from bs4 import BeautifulSoup</code>
-
对 HTML 文档进行解析:
<code class="python">soup = BeautifulSoup(html_doc, "html.parser")</code>
-
定位当前标签:
<code class="python">current_tag = soup.find("div", {"class": "example"})</code> -
获取下一个标签:
<code class="python">next_tag = current_tag.next_sibling</code>
举例:
以下示例展示了如何获取 <div> 标签的下一个兄弟标签:
<code class="python">html_doc = "<div class='example'>Hello</div><p>World</p>"
soup = BeautifulSoup(html_doc, "html.parser")
current_tag = soup.find("div", {"class": "example"})
next_tag = current_tag.next_sibling
print(next_tag.name) # 输出 "p"</code>注意:
- 如果下一个标签是文本节点,则
next_sibling将返回None。 -
next_sibling只获取直接的下一个标签,如果要获取更远处的标签,需要使用next_siblings属性。











