오류 해결모음

셀레니움 Message: invalid selector , [object Text]. It should be an element.

슬픈 문과생 2023. 2. 28. 11:13

주피터노트북과 함께하는

문과의 파이썬 코딩

 

오늘도 신나게 웹 스크래핑을 하다가

건방진 에러가 나와서 뚝배기를 깨버렸다


 

 

 

목차

     

    <Invalid Error, It should be an element.>

    yahoo finance

     

    오늘 나의 목표 야후 파이낸스의

    Company Profile부분에서 Description

    텍스트를 크롤링하려한다.

     

    평소에 XPATH로 긁어오는 방식을

    선호해서 똑같이 하려던 찰나

    from selenium import webdriver
    from selenium.webdriver.common.by import By
    
    options = webdriver.ChromeOptions()
    options.add_argument('headless')
    options.add_argument('window-size=1920x1080')
    options.add_argument("disable-gpu")
    options.add_argument("user-agent=Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko")
    
    path = "./chromedriver.exe"
    driver = webdriver.Chrome(path,options=options)
    
    driver.get(f"https://finance.yahoo.com/quote/LHDX/profile?p=LDHX")
    a = driver.find_element(By.XPATH,"""//*[@id="Col1-0-Profile-Proxy"]/section/section[2]/p/text()""")

    .

    .

    .

    .

    아래와 같은 에러가 나왔다.

    InvalidSelectorException: Message: invalid selector:
    The result of the xpath expression "//*[@id="Col1-0-Profile-Proxy"]
    /section/section[2]/p/text()" is: [object Text]. It should be an element.
      (Session info: headless chrome=110.0.5481.178)
    Stacktrace:
    Backtrace:
    	(No symbol) [0x00D937D3]
    	(No symbol) [0x00D28B81]
    	(No symbol) [0x00C2B36D]
    	(No symbol) [0x00C2E0FB]
    	(No symbol) [0x00C2DFD0]

     

     

    뭘 잘못 선택했다고 하는것 같아서

    XPATH, full XPATH 바꿔가며

    이렇게 저렇게 시도를 해보던중...

     

     


    <Error 해결법>

     

     

     

    driver.get(f"https://finance.yahoo.com/quote/LHDX/profile?p=LDHX")
    a = driver.find_element(By.XPATH,"""//*[@id="Col1-0-Profile-Proxy"]/section/section[2]/p/text()""")

    html element가 아닌 텍스트 컨테이너를

    지정해서 생긴 문제였다.

     

     

    아래와 같이 그 element를 지정한 뒤.text를 붙여

    테스트를 크롤링하면 해결 끝!

    driver.get(f"https://finance.yahoo.com/quote/LHDX/profile?p=LDHX")
    a = driver.find_element(By.XPATH,"""//*[@id="Col1-0-Profile-Proxy"]/section/section[2]/p""").text

     

    [실행 결과]

    [최종 코드]

    from selenium import webdriver
    from selenium.webdriver.common.by import By
    
    options = webdriver.ChromeOptions()
    options.add_argument('headless')
    options.add_argument('window-size=1920x1080')
    options.add_argument("disable-gpu")
    options.add_argument("user-agent=Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko")
    
    path = "./chromedriver.exe"
    driver = webdriver.Chrome(path,options=options)
    
    driver.get(f"https://finance.yahoo.com/quote/LHDX/profile?p=LDHX")
    a = driver.find_element(By.XPATH,"""//*[@id="Col1-0-Profile-Proxy"]/section/section[2]/p""").text
    print(a)