LoginSignup
1
1

More than 1 year has passed since last update.

Seleniumでのスクレイピングにて非同期で受信される要素のテキストを取得する

Last updated at Posted at 2022-06-27

問題点

Webサイトで要素の中身が元々空であり、非同期であとから中身が表示されるものがある。
これにより、待機時間が短いと空を取得してしまう。

実行環境

M1 Macbook Air
macOS Monterey 12.4
Python 3.10

解決方法

取得したいテキストが分かっている場合

そのテキストが表示されるまで待機する

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

options = webdriver.ChromeOptions()
options.add_argument('--headless')
driver = webdriver.Chrome(options=options)

driver.get('https://example.com/index.html')
# ページが読み込まれるまで待機
wait = WebDriverWait(driver, 10)
wait.until(EC.presence_of_all_elements_located)

# 取得したいテキストが表示されるまで待機する
wait.until(EC.text_to_be_present_in_element((By.XPATH, "取得したい要素のXpath"), "取得したいテキスト"))
# スクレピングする
result = driver.find_element(By.XPATH, "取得したい要素のxpath")

print(result.text)

これはかなり良き。

取得したいテキストが分からない場合

refresh()を利用して取得できるまでぶん回す。

import time
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

options = webdriver.ChromeOptions()
options.add_argument('--headless')
driver = webdriver.Chrome(options=options)

driver.get('https://example.com')
# ページが読み込まれるまで待機
wait = WebDriverWait(driver, 10)
wait.until(EC.presence_of_all_elements_located)

# 取得できるまで繰り返す(一応無限ループはやめとく)
for i in range(50):
    # 待機時間
    time.sleep(5)
    # スクレピングする
    result = driver.find_element(By.XPATH, "取得したい要素のxpath")
    
    # スクレピングしたテキストが取得できていたら抜ける
    if result.text != '':
        break
    # テキストの中身が空だったらページを更新する
    driver.refresh()

print(result.text)

ゴリ押し感がすごいw
うーん、もっと良い方法ないかなあ

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