NEWStandard createTask and in.php APIs. Change the address and you are connected.View API docs
GATESOLVER

Web scraping

Web scraping with Selenium and Python

Selenium drives a real browser, so it sees pages exactly as visitors do. The challenge is making that browser behave predictably in a script. Waits, locators and a few habits make the difference.

When Selenium is the right tool

Use Selenium when the data appears only after JavaScript runs, when you must click, type or scroll to reach it, or when a page only works in a full browser. If the content is already in the HTML, or comes from a JSON endpoint you can call, plain HTTP is faster and cheaper; see Scrapy vs Selenium for that trade off.

Setup

pip install selenium

Since Selenium 4.6, Selenium Manager downloads a matching browser driver automatically, so you no longer install chromedriver by hand. You still need Chrome or another supported browser on the machine.

from selenium.webdriver import Chrome as ChromeDriver, ChromeOptions

def start_browser(headless: bool = True) -> ChromeDriver:
    opts = ChromeOptions()
    if headless:
        opts.add_argument("--headless=new")
    opts.add_argument("--window-size=1440,960")
    opts.add_argument("--lang=en-US")
    opts.page_load_strategy = "eager"
    return ChromeDriver(options=opts)

--headless=new selects Chrome's current headless mode, which renders pages like the normal browser. A fixed window size keeps layouts stable, since many sites change their markup at different widths. The eager load strategy returns control once the DOM is ready, without waiting for every image; your explicit waits then decide when the data is there.

Explicit waits instead of sleeps

The single most common Selenium bug is reading an element before the page has created it. time.sleep(5) hides the problem until a slow day. An explicit wait polls for a condition and continues the moment it is true.

from selenium.webdriver.common.by import By as Find
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as until_ec

def open_and_wait(drv, url: str, css: str, seconds: int = 20):
    drv.get(url)
    return WebDriverWait(drv, seconds).until(
        until_ec.visibility_of_all_elements_located((Find.CSS_SELECTOR, css)))

Pick the condition that matches what you need: presence_of_element_located when the element only has to exist in the DOM, visibility_of... when it must be shown, element_to_be_clickable before a click. Avoid mixing implicit waits with explicit ones; the combination produces confusing timeouts.

Locators that survive redesigns

Prefer locators tied to meaning rather than layout:

  • Best: ids, data-* attributes, name, ARIA labels.
  • Good: short CSS selectors on semantic classes, such as article.listing h2.
  • Fragile: long absolute XPaths copied from DevTools, or generated class names like css-1x2y3z.

XPath is useful when you need text matching, for example //button[normalize-space()='Show more'], or relations such as "the cell after the one labeled Price". Our entry on CSS selectors covers the syntax.

Reading data efficiently

Every find_element and .text call is a round trip to the browser. On a page with hundreds of rows that adds up. Two faster options: run one JavaScript snippet that returns all values at once, or hand page_source to a fast parser.

rows = drv.execute_script("""
  return [...document.querySelectorAll('article.listing')].map(a => ({
    title: a.querySelector('h2')?.innerText.trim() ?? null,
    price: a.querySelector('[data-price]')?.dataset.price ?? null,
  }));
""")

from lxml import html as lxml_html
tree = lxml_html.fromstring(drv.page_source)
titles = tree.xpath("//article[@class='listing']//h2/text()")

Both read the rendered DOM in one step. The JavaScript route returns Python lists and dictionaries directly; the lxml route lets you reuse parsing code from your HTTP scrapers.

Infinite scroll

Pages that load more items as you scroll need a loop: scroll to the bottom, wait for new items, stop when nothing new appears.

def scroll_until_stable(drv, item_css: str, max_rounds: int = 30) -> int:
    count = len(drv.find_elements(Find.CSS_SELECTOR, item_css))
    for _ in range(max_rounds):
        drv.execute_script("window.scrollTo(0, document.body.scrollHeight);")
        try:
            WebDriverWait(drv, 6).until(
                lambda d: len(d.find_elements(Find.CSS_SELECTOR, item_css)) > count)
        except Exception:
            break
        count = len(drv.find_elements(Find.CSS_SELECTOR, item_css))
    return count

The wait uses a lambda as its condition, which any callable returning a truthy value can be. The round limit stops pages that load forever. The note on scraping infinite scroll lists other signals to stop on, such as an "end of results" marker.

Paging without stale elements

After you click "Next", the old page's elements are gone. Any reference you still hold raises StaleElementReferenceException. Use that to your advantage: wait until an element from the old page goes stale, which proves the new page has replaced it.

from selenium.common.exceptions import TimeoutException

def next_page(drv) -> bool:
    marker = drv.find_element(Find.CSS_SELECTOR, "article.listing")
    buttons = drv.find_elements(Find.CSS_SELECTOR, "a[rel=next]")
    if not buttons:
        return False
    buttons[0].click()
    try:
        WebDriverWait(drv, 15).until(until_ec.staleness_of(marker))
    except TimeoutException:
        return False
    return True

Re-find elements after every navigation instead of reusing old references, and the stale element errors disappear.

Cookie banners and overlays

Consent banners, newsletter popups and region selectors often cover the content or intercept clicks, which shows up as ElementClickInterceptedException. Handle them right after the first page load: wait briefly for the banner's accept button with element_to_be_clickable, click it if it appears, and continue if it does not. Because the choice is usually stored in a cookie, one click per browser session is enough. If a banner keeps returning, check whether you are starting a fresh profile for every page; reusing one browser for a batch keeps such cookies and makes the session look more like a normal visit.

Running several browsers

Selenium has no built in concurrency, but you can run a few browsers side by side with concurrent.futures.ThreadPoolExecutor, giving each worker its own driver. Two to four workers on an ordinary machine is a sensible start, since each Chrome instance needs its own memory. For larger jobs, Selenium Grid spreads browsers across machines with the same code, using webdriver.Remote instead of webdriver.Chrome.

Cleanup and resources

Always end with drv.quit() in a finally block. A crashed script that leaves Chrome running will slowly fill a server's memory. If you run many pages, reuse one browser for a batch and restart it every few hundred pages; long sessions accumulate memory. Our note on headless vs headful explains when to watch the browser while debugging.

Detection and CAPTCHAs

An automated Chrome exposes signs such as navigator.webdriver being true, and some sites react with a challenge. Two things help. First, behave like a visitor: realistic pacing, a normal window size, and no needless requests. Second, when a token CAPTCHA appears, solve it through an API and place the token in the page with execute_script; reCAPTCHA expects it in the g-recaptcha-response textarea, Turnstile in cf-turnstile-response. The Selenium integration shows both, including how to call the site's callback when the form waits for one.

A browser loads every asset on a page, so Selenium scraping puts more load on a site than plain requests. Keep concurrency low, scrape public data, and stop if the site signals strain.

Common questions

Do I still need to download chromedriver?

No, not since Selenium 4.6. Selenium Manager downloads a matching driver automatically when you create the browser.

Why is time.sleep a bad way to wait in Selenium?

It waits too long on fast days and not long enough on slow ones. Explicit waits continue as soon as the condition is met.

How do I avoid StaleElementReferenceException?

Find elements again after each navigation or DOM update, and wait for an old element to go stale to confirm the page changed.

What does --headless=new do?

It runs Chrome's current headless mode, which renders pages like the visible browser and avoids old headless differences.

How can I read many rows faster?

Return all values with one execute_script call, or parse driver.page_source with lxml, instead of calling find_element per cell.

Keep reading