selenium 이용 중 페이지 로딩을 기다리는 2가지 방법

#1. 항목을 가져와야 하는데, 오류 발생

object of type 'WebElement' has no len()

이런 경우, elems = driver.find_element(By.CLASS_NAME, '클래스명') 로 elems를 선언할 때, 함수를 단수형태로 가져왔기에 배열이 아니라, 단순(1개의) 항목이라 len(elems) 하면 오류가 발생한다. driver.find_elements(By.CLASS_NAME, '클래스명') 처럼 복수로 가져올 수 있도록 수정
#2. Xpath로 설정했는데, WebDriver(selenium)이 항목을 식별할 수 없다.

Message: no such element: Unable to locate element:

이런 경우, 문서 구조에서 iframe 을 포함하는 것인지 확인. 네이버 카페의 경우 "cafe_main" 이라는 iframe내에 게시글들이 들어가 있는 구조라서,
iframe = driver.find_element(By.ID, 'cafe_main')
driver.switch_to.frame(iframe)
이런식으로 driver를 switch해줘야 함. 만약 다시 원래 페이지 구조로 돌아오려면,
driver.switch_to_default_content()를 호출하면 됨.

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.keys import Keys
from webdriver_manager.chrome import ChromeDriverManager
import time
import datetime as d
from openpyxl import Workbook

xlsx = Workbook()
sheet = xlsx.active
sheet.append(['Title', 'Link', 'Published date'])

try:
    options = Options()
    options.add_experimental_option("detach", True)
    options.add_experimental_option("excludeSwitches", ["enable-logging"])
    service = Service(ChromeDriverManager().install())
    driver = webdriver.Chrome(service=service, options=options)
    
    keyword = '유형자산'                      
    driver.get('https://cafe.naver.com/parksamaccount')

    elem = driver.find_element(By.ID, 'topLayerQueryInput') 
    elem.send_keys(keyword)
    elem.send_keys(Keys.RETURN)

    iframe = driver.find_element(By.ID, 'cafe_main')
    driver.switch_to.frame(iframe)

    articles = driver.find_elements(By.CLASS_NAME, 'td_article')
    print(len(articles))
    for article in articles :
        title = article.find_element(By.TAG_NAME, "a")
        print(title.text)    
except Exception as e :
    print(e)    
finally :
    #driver.quit()
    print('ee')

#3. 책의 소스 또는 블로그의 소스가 실행이 안되는 경우, 참고하는 자료의 버전을 확인하고 버전을 맞춰본다.
print(library.__verison__) 확인후 재설치

Posted by 목표를 가지고 달린다
,