要素の存在判定にfind_elementsを使ってはいけない
find_elementの実行時間: 0.993401 秒
find_elementsの実行時間: 6.281310 秒
test.py
import time
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
driver.get("https://jp.mercari.com/item/m98015773873")
# find_elementを使った場合
start_time_find_element = time.time()
try:
element = driver.find_element(By.XPATH, "//mer-item-thumbnail")
except NoSuchElementException:
element = None
end_time_find_element = time.time()
# find_elementsを使った場合
start_time_find_elements = time.time()
elements = driver.find_elements(By.XPATH, "//mer-item-thumbnail")
element = elements[0] if elements else None
end_time_find_elements = time.time()
# 実行時間を比較
find_element_time = end_time_find_element - start_time_find_element
find_elements_time = end_time_find_elements - start_time_find_elements
print(f"find_elementの実行時間: {find_element_time:.6f} 秒")
print(f"find_elementsの実行時間: {find_elements_time:.6f} 秒")
driver.quit()