Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Scrape JavaScript Rendered Websites with Python

· 5 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

Many modern websites load content dynamically with JavaScript, so a simple HTTP request only returns the empty shell of the page. To scrape these sites, you need a tool that executes the JavaScript and waits for the content to appear. This guide shows you how to do that with Python, using Selenium and Playwright — two popular browser automation libraries. You'll learn the core steps, common pitfalls, and how to handle typical problems.

What You'll Need

  • Python 3.7 or newer installed on your system.
  • pip (Python's package installer) — usually comes with Python.
  • A code editor or IDE (like VS Code, PyCharm, or even Notepad).
  • Basic knowledge of Python, HTML, and CSS selectors.
  • For Selenium: the selenium package and a WebDriver (e.g., ChromeDriver for Chrome).
  • For Playwright: the playwright package and the browser binaries (playwright install).

Step-by-Step

  1. Choose your tool. Selenium is older and more widely used; Playwright is newer, faster, and has better waiting mechanisms. Both work well. This guide covers both, but you only need one.
  2. Install the library.
    • For Selenium: pip install selenium
    • For Playwright: pip install playwright and then playwright install to download browser binaries.
  3. Set up the browser driver (Selenium only). Download the matching WebDriver for your browser (e.g., ChromeDriver for Chrome) and place it in your PATH, or specify its location in the code.
  4. Write a basic script that opens a page.
    • Selenium example:
      from selenium import webdriver
      driver = webdriver.Chrome()
      driver.get("https://example.com")
      print(driver.title)
      driver.quit()
    • Playwright example:
      from playwright.sync_api import sync_playwright
      with sync_playwright() as p:
          browser = p.chromium.launch()
          page = browser.new_page()
          page.goto("https://example.com")
          print(page.title())
          browser.close()
  5. Wait for the dynamic content to load. JavaScript takes time to fetch data and render it. Use explicit waits instead of fixed sleeps.
    • Selenium: WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, "#content")))
    • Playwright: page.wait_for_selector("#content")
  6. Extract the data. Once the element is present, grab the text or attributes.
    • Selenium: element = driver.find_element(By.CSS_SELECTOR, ".item"); text = element.text
    • Playwright: element = page.query_selector(".item"); text = element.inner_text()
  7. Handle multiple elements. Use find_elements (Selenium) or query_selector_all (Playwright) to get a list, then loop through them.
  8. Deal with infinite scroll or "Load More" buttons. Scroll to the bottom or click the button repeatedly until no new content appears. In Selenium, you can execute JavaScript to scroll: driver.execute_script("window.scrollTo(0, document.body.scrollHeight)"). In Playwright, use page.mouse.wheel(0, 10000).
  9. Store the data. Save to CSV, JSON, or a database. Use Python's built-in csv or json modules.
  10. Clean up. Always close the browser in a finally block or use a context manager to avoid leaving processes running.

Common Mistakes

  • Using time.sleep() instead of explicit waits. Fixed sleeps are unreliable; the page might load faster or slower than your sleep time.
  • Not waiting for the right condition. Waiting for an element to be present isn't enough if it's still empty. Wait for it to be visible or contain text.
  • Scraping too fast. Sending too many requests in a short time can get your IP blocked. Add delays between requests.
  • Ignoring the robots.txt file. Check if the site allows scraping. Some sites explicitly disallow it.
  • Not handling iframes. Some content is inside iframes; you need to switch to the iframe first.
  • Forgetting to close the browser. This leaves memory and processes hanging.

Tips

  • Use headless mode for speed. Both Selenium and Playwright can run without a visible browser window. In Selenium: options.add_argument("--headless"). In Playwright: p.chromium.launch(headless=True).
  • Leverage CSS selectors and XPath. They are powerful for locating elements. Inspect the page in your browser's dev tools to find the right selectors.
  • Use Playwright's auto-waiting. Playwright automatically waits for elements to be actionable, which reduces the need for explicit waits.
  • Cache the page HTML. If you need to re-parse, save the HTML to a file to avoid re-scraping.
  • Rotate user agents and use proxies if necessary. This helps avoid detection, but be respectful and follow the site's terms.

Troubleshooting

  • Element not found. Double-check the selector. The element might be inside an iframe, or the page might not have loaded yet. Increase the wait time and try a more specific selector.
  • Browser won't start. Ensure the WebDriver version matches your browser version (Selenium). For Playwright, run playwright install again.
  • Page loads but content is missing. The site might use lazy loading. Scroll down to trigger loading, or wait for a specific network request to finish.
  • Getting blocked or receiving CAPTCHAs. Slow down, use headless mode, and consider using a residential proxy. If it's a CAPTCHA, you might need to use a service like 2Captcha, but that's beyond this guide.
  • Script works but data is empty. The element might be present but not yet populated. Wait for text to appear using text_to_be_present_in_element (Selenium) or wait_for_function (Playwright).
  • Memory leaks. If you're scraping many pages, restart the browser periodically or use a new context/page for each URL.

Frequently Asked Questions

Is it legal to scrape JavaScript-rendered websites?

It depends on the website's terms of service and your jurisdiction. Always check the site's robots.txt and terms. Public data is generally safer to scrape, but you should still be respectful and avoid overloading the server.

What's the difference between Selenium and Playwright?

Selenium is more established and supports multiple browsers, but Playwright is faster, has better waiting mechanisms, and offers a cleaner API. For new projects, Playwright is often recommended.

Can I scrape a site that requires login?

Yes, you can automate login by filling in the credentials fields. However, this may violate the site's terms, and you should be careful with your credentials. Use environment variables to store them securely.

How do I handle infinite scroll pages?

Scroll to the bottom, wait for new content to load, and repeat until no new elements appear. You can also look for a "Load More" button and click it until it disappears.

Why do I get an empty page with requests but not with Selenium?

Because requests doesn't execute JavaScript. The content is loaded dynamically via JS, so you need a browser engine to render it. That's why you use Selenium or Playwright.

Can I use this to scrape data for commercial purposes?

Possibly, but you must ensure you have the right to use the data. Always read the website's terms of service and consider copyright and data protection laws. When in doubt, contact the site owner.