Why not login to Qiita and try out its useful features?

We'll deliver articles that match you.

You can read useful information later.

6
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

WEBサイトのデータ取得

はじめに

スクレイピングで遊んでいた時に便利だなと思ったことをメモとして書き残しときます。

find_next_sibling()

find_next_sibling() メソッドは、指定した要素の直後にある兄弟要素(同じ親要素を持つ要素)を取得します。

from bs4 import BeautifulSoup

html = """
<div class="container">
    <p>First paragraph</p>
    <p>Second paragraph</p>
    <p>Third paragraph</p>
</div>
"""

soup = BeautifulSoup(html, 'html.parser')

# 最初の <p> 要素を取得
first_paragraph = soup.find('p')

# 最初の <p> 要素の次にある兄弟 <p> 要素を取得
second_paragraph = first_paragraph.find_next_sibling('p')

print(first_paragraph.text)  # 出力: First paragraph
print(second_paragraph.text) # 出力: Second paragraph

最初の<p>要素を取得し、その次にある兄弟要素である2番目の<p>要素を取得しています。この場合、最初の<p>要素の次にある兄弟要素は "Second paragraph" です。

これで特定の要素の次の要素が取得できます。 可変的なものでidやclassから取得できない時に便利なので覚えておくといいことあるかも。


記事を読んでくださった方は、是非弊社開発課のXもフォローしてね
毎日エンジニアに向けた情報発信を行っています
https://twitter.com/tech_cin

6
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up

Qiita Conference 2025 will be held!: 4/23(wed) - 4/25(Fri)

Qiita Conference is the largest tech conference in Qiita!

Keynote Speaker

ymrl、Masanobu Naruse, Takeshi Kano, Junichi Ito, uhyo, Hiroshi Tokumaru, MinoDriven, Minorun, Hiroyuki Sakuraba, tenntenn, drken, konifar

View event details
6
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?