0Pricing
Web Scraping & Bots · 강의

JavaScript에서 데이터 추출

AJAX 호출과 단일 페이지 애플리케이션의 콘텐츠를 포함해 JavaScript가 생성하거나 로드한 데이터를 가져오는 방법을 학습합니다.

JavaScript에서 데이터 추출은(는) CoddyKit의 무료 Web Scraping & Bots 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Web Scraping & Bots 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Web Scraping & Bots 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Dynamic Web Content Explained

Many modern websites don't load all their content at once. Instead, they use JavaScript to fetch data and update the page after it initially loads. This is called dynamic content.

Traditional scraping tools like Requests and BeautifulSoup only see the initial HTML. They miss anything JavaScript loads later.

JavaScript's Role in Loading

JavaScript can load new data in several ways:

  • AJAX Calls: Asynchronous JavaScript and XML. The browser requests data from a server in the background without reloading the entire page.
  • DOM Manipulation: JavaScript directly adds, removes, or modifies elements in the page's structure (Document Object Model).
  • Single-Page Applications (SPAs): Entire websites built to dynamically load content and navigate without full page refreshes.

This dynamic loading makes scraping more complex.

When Requests & BS4 Fall Short

When you use Python's requests library, you get the raw HTML that the server sends initially. If a website then uses JavaScript to load more data, that data won't be in the HTML you received.

BeautifulSoup can only parse the HTML it's given. It can't execute JavaScript to fetch additional content or wait for it to appear.

Selenium for Dynamic Content

This is where Selenium becomes essential. Selenium controls a real web browser (like Chrome or Firefox) programmatically.

When Selenium opens a page, the browser executes all JavaScript, including any AJAX calls or DOM manipulations. This means Selenium sees the fully rendered page, just like a human user would.

Waiting for Elements to Appear

Since content loads dynamically, it might not be immediately available when Selenium first loads a page. You need to tell Selenium to wait until a specific element or condition is met before trying to extract data.

If you don't wait, your script might try to find an element before JavaScript has rendered it, leading to errors or missing data.

Using Explicit Waits

Selenium's WebDriverWait combined with ExpectedConditions (EC) allows you to set explicit waits. This tells Selenium to wait for a maximum amount of time until a certain condition is true.

Common conditions include waiting for an element to be visible, clickable, or present in the DOM.

Try running this example:

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

def main():
    driver = webdriver.Chrome()
    driver.get("https://www.selenium.dev/selenium/web/dynamic.html")

    # Click a button that will make an element appear after a delay
    driver.find_element(By.ID, "adder").click()

    # Wait up to 10 seconds for the new element to appear
    try:
        new_element = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.ID, "box0"))
        )
        print("New element found:", new_element.text)
    except Exception as e:
        print("Element not found within time limit:", e)

    driver.quit()

if __name__ == "__main__":
    main()

Extracting Rendered Data

Once you've successfully waited for dynamic content to appear, extracting the data is similar to how you'd extract from static content using Selenium.

You can use methods like find_element(By.ID, "id_name"), find_element(By.CLASS_NAME, "class_name"), or find_element(By.CSS_SELECTOR, "css_selector") to locate the elements. Then, you can retrieve their text content or attributes.

Code: Get Dynamic Text

This example shows how to wait for an element and then extract its text. Imagine a page where a "Loading..." message changes to actual data after a few seconds.

Try running this example:

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

def main():
    driver = webdriver.Chrome()
    # Using a simple test page that changes content
    driver.get("https://www.selenium.dev/selenium/web/dynamic.html")

    # Click button to reveal content
    driver.find_element(By.ID, "reveal").click()

    # Wait for the content to be visible
    try:
        # The 'revealed' div becomes visible
        revealed_div = WebDriverWait(driver, 10).until(
            EC.visibility_of_element_located((By.ID, "revealed"))
        )
        print("Revealed content:", revealed_div.text)
    except Exception as e:
        print("Revealed content not found:", e)

    driver.quit()

if __name__ == "__main__":
    main()

Scraping Single-Page Apps

Single-Page Applications (SPAs) are websites that load a single HTML page and then dynamically update content as the user interacts. Navigation within an SPA often doesn't involve full page reloads.

Selenium handles SPAs well because it acts as a full browser. You interact with elements (like clicking navigation links) and Selenium executes the JavaScript, updating the DOM. You then apply the same waiting and extraction techniques.

Quick Check on Waiting

When scraping dynamic content that appears after the initial page load, which Selenium technique is crucial to ensure the content is available before attempting to extract it?

Recap: Dynamic Data Extraction

Great job! You've learned how to tackle dynamic web content:

  • Many sites use JavaScript for AJAX calls, DOM manipulation, and SPAs.
  • Traditional tools like Requests and BeautifulSoup cannot execute JavaScript.
  • Selenium, by controlling a full browser, can render JavaScript.
  • Explicit waits are essential to ensure dynamically loaded content is present before extraction.

This skill opens up a vast number of modern websites for your scraping projects!

자주 묻는 질문

“JavaScript에서 데이터 추출” 강의는 무료인가요?

네 — “JavaScript에서 데이터 추출” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Web Scraping & Bots 강의 전체를 잠금 해제할 수 있습니다. Web Scraping & Bots 강의에는 총 4개의 강의가 포함되어 있습니다.

“JavaScript에서 데이터 추출”에서 뭘 배우나요?

AJAX 호출과 단일 페이지 애플리케이션의 콘텐츠를 포함해 JavaScript가 생성하거나 로드한 데이터를 가져오는 방법을 학습합니다. 브라우저에서 직접 실행하는 실습 코드로 Web Scraping & Bots을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Web Scraping & Bots을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Web Scraping & Bots은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.

“JavaScript에서 데이터 추출” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Web Scraping & Bots 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Web Scraping & Bots 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. Selenium 입문
  2. 브라우저 상호 작용 자동화
  3. JavaScript에서 데이터 추출
  4. 동적 페이지 대기 전략
← Web Scraping & Bots(으)로 돌아가기