LoginSignup
0
1

More than 1 year has passed since last update.

【Selenium】同じClassが2つ以上存在した場合に、それらの中から1つだけ抽出する方法

Posted at

Seleniumでデータスクレイピングをする時に、同じクラス名が複数ある場合最初に1つだけしか取得できないということにハマりました。
今回はその解決策をメモとして保存しておきます。

今回のケース

sample.html
<div>
 <p class=food>りんご</div>
 <p class=food>かき</div>
 <p class=food>もも</div>
</div>

上記のようなクラス以外に差別化できるものがない場合にどうしたらいいか分からなく時間を使ってしまいました。

解決策

test.py
from selenium import webdriver
from selenium.webdriver.common.by import By

apple = driver.find_elements(By.CLASS_NAME, "food")
apple = house_year[0].text
peach = driver.find_elements(By.CLASS_NAME, "food")
peach = house_width[2].text

上記で動作しました。
誰かの役に立てれば嬉しいです。
指摘があれば、コメントください

0
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
0
1