Introduction
In Part 1 of this series, we used requests and BeautifulSoup to extract quotes from a webpage. The information we wanted was already present in the HTML response, so we could find the right tags and read their text.
This time, we are moving on to websites where collecting data involves interacting with the page. We might need to enter a search term, submit a login form, click Next, or wait while JavaScript builds the results.
For these workflows, we will introduce Selenium, which lets Python control a browser. We will first demonstrate what our earlier approach misses, then use Selenium to load content, enter information and move between pages. BeautifulSoup will still help us extract the final data.
What actually makes a page difficult to scrape
There is one distinction worth clearing up from Part 1: a website having a backend or database does not, by itself, make it difficult for BeautifulSoup to handle.
A Flask or Django application can query a database and return a complete HTML page. We can fetch that response and parse it just as we did before. MDN's explanation of dynamic websites describes this server-side approach.
The more relevant question is whether the elements we want are already in the response, or whether the browser creates them later. JavaScript can build those elements from data embedded in the page or fetched through another request.
It helps to separate the jobs our tools perform:
| Tool | Its job in this tutorial |
| Requests | Send HTTP requests and receive responses. It does not run the page's JavaScript. |
| BeautifulSoup | Parse the HTML we give it and find elements. It does not click, type or execute JavaScript. |
| Selenium | Control a browser that runs JavaScript and can interact with the page. |
A search box or login form is not automatic proof that Selenium is necessary. Some forms can be handled with HTTP requests, parameters, cookies and the appropriate form data. Here, we are learning the browser-based approach, which is useful when we need to reproduce the visible workflow.
Showing the limitation with the same quotes website
The Quotes to Scrape sandbox includes a JavaScript version and a delayed version. That gives us a useful progression from the original example without changing the dataset.
Open the delayed version in a browser. After its deliberate delay of about ten seconds, the quotes appear. Now try our earlier approach:
import requests
from bs4 import BeautifulSoup
url = "https://quotes.toscrape.com/js-delayed/"
response = requests.get(url, timeout=15)
response.raise_for_status()
soup = BeautifulSoup(response.text, "html.parser")
print(len(soup.select("div.quote")))With the current page, this prints 0.
The request succeeded. The missing piece is that the browser normally runs JavaScript to create the quote elements, while our script only parses the downloaded HTML. On this particular demo, the quote data is actually embedded in a JavaScript block; the div.quote elements have not been created yet.
This also explains why the browser's Inspect panel can show elements that our scraper cannot find. Inspect displays the current document structure, including changes made by JavaScript. response.text contains the response we downloaded.
Adding time.sleep(10) after requests.get() will not change that response. Waiting in Python does not make JavaScript execute inside BeautifulSoup.
Opening a browser with Selenium
Install the packages in your Python environment:
python -m pip install selenium beautifulsoup4 requestsThe examples below use Chrome. Have Chrome installed, and keep the browser visible while learning so you can see each action. Modern Selenium includes Selenium Manager, which normally handles the matching driver automatically. Its initial setup may need internet access to download the driver.
Here is a complete first example:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
driver = webdriver.Chrome()
try:
driver.get("https://quotes.toscrape.com/js-delayed/")
wait = WebDriverWait(driver, 20)
quotes = wait.until(
EC.visibility_of_all_elements_located(
(By.CSS_SELECTOR, "div.quote")
)
)
print(f"Found {len(quotes)} visible quote cards")
finally:
driver.quit()webdriver.Chrome() starts the browser, and driver.get() opens the page. finally makes sure we close the browser even if a later step fails. The Selenium first-script guide covers this basic lifecycle.
Waiting for the right thing
The most important new line is wait.until(...).
A browser finishing its initial navigation does not mean every JavaScript-generated result is ready. An explicit wait repeatedly checks a condition until it succeeds or reaches its timeout. In our example, we wait for matching quote cards to be visible. Selenium's waiting guide explains why this is more reliable than guessing a fixed delay.
The condition should match the next action. Wait for a field to be visible before typing, a button to be visible and enabled before clicking, or a result state to appear before extracting data.
The word all in visibility_of_all_elements_located refers to the elements currently found by that selector. It does not prove that a website has finished loading every possible result. It suits this demo, where the quotes are inserted together. Other pages may need a loading indicator to disappear or an expected result count to appear.
We will use explicit waits throughout. A separate pause can still pace requests politely; that serves a different purpose from detecting readiness.
Entering a search term
Let's put keyboard input into practice. Scrape This Site's hockey exercise has a real search field for team names.
The sequence is straightforward: find the field, clear its existing value, type a term, submit the form and wait for the new results.
The following is a separate example you can run in its own file:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
driver = webdriver.Chrome()
try:
wait = WebDriverWait(driver, 20)
driver.get("https://www.scrapethissite.com/pages/forms/")
old_table = wait.until(
EC.presence_of_element_located((By.CSS_SELECTOR, "table.table"))
)
search_box = wait.until(EC.element_to_be_clickable((By.ID, "q")))
search_box.clear()
search_box.send_keys("Boston")
wait.until(
EC.element_to_be_clickable((By.CSS_SELECTOR, "form input[type='submit']"))
).click()
# This form navigates to a new document.
wait.until(EC.staleness_of(old_table))
rows = wait.until(
EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "tr.team"))
)
for row in rows:
name = row.find_element(By.CSS_SELECTOR, "td.name").text
year = row.find_element(By.CSS_SELECTOR, "td.year").text
print(name, year)
finally:
driver.quit()Here, By.ID, "q" identifies this particular search field. The result rows use tr.team, with the team name in td.name and the season in td.year. These selectors belong to this demo; inspect a different site before adapting them. We wait for the old table to detach before reading the new rows, so we cannot accidentally print the previous results.
The key methods are clear() and send_keys(). Buttons and links use click(). These are standard Selenium element interactions.
This particular search form returns another HTML page. Selenium can operate it, but HTTP requests could also reproduce the search. On a JavaScript search interface, the URL might stay unchanged while the results update. There, wait for a site-specific signal, such as the submitted query appearing in a results heading and the loading indicator disappearing. An old result card being present is not enough.
Submitting a login form
Login follows the same basic pattern: locate the fields, enter the credentials, submit and check for a state that indicates success.
For practice, use Quotes to Scrape's demo login. Its sandbox documentation explicitly says that any username and password work. Use made-up, nonempty values such as demo; do not enter a real password on a practice site.
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
driver = webdriver.Chrome()
try:
wait = WebDriverWait(driver, 20)
driver.get("https://quotes.toscrape.com/login")
username = wait.until(
EC.visibility_of_element_located((By.ID, "username"))
)
username.send_keys("demo")
driver.find_element(By.ID, "password").send_keys("demo")
wait.until(
EC.element_to_be_clickable((By.CSS_SELECTOR, "input[type='submit']"))
).click()
wait.until(
EC.visibility_of_element_located((By.CSS_SELECTOR, "a[href='/logout']"))
)
print("Logged in successfully")
finally:
driver.quit()We check for the Logout link after submitting. Clicking Login alone does not prove the credentials were accepted.
The browser handles the form submission, including its hidden CSRF token, and retains the session cookie issued by the site. Further navigation using the same driver can use that session. Opening an unrelated requests.Session() would not automatically share it.
On a real authorised workflow, supply the correct credentials through an environment variable or a password prompt such as getpass.getpass(), rather than committing them to your script. MFA and other interactive checks may need an approved manual step. Logging in does not itself grant permission to collect every piece of data an account can view.
This login exercise is separate from the JavaScript quotes example. Those public quote pages do not require authentication.
Moving between pages and extracting the results
Now we can put browser navigation and extraction together.
There is a subtle pagination problem: immediately after clicking Next, a scraper might still see the old results. Waiting for any quote card would then succeed too early.
On the delayed quotes demo, Next loads a new document. We can remember a card from the old page, click Next, wait until that old element is detached, then wait for the new quote cards. Selenium calls the detachment check staleness_of.
After the new cards appear, driver.page_source gives us an HTML snapshot of the current document. We pass that snapshot to BeautifulSoup and use the familiar selectors from Part 1. Take a fresh snapshot after each navigation; an existing BeautifulSoup object will not update itself as the browser changes.
Save this complete example as scrape_dynamic_quotes.py:
import json
import time
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
START_URL = "https://quotes.toscrape.com/js-delayed/"
MAX_PAGES = 3
def extract_quotes(html, source_url):
soup = BeautifulSoup(html, "html.parser")
records = []
for card in soup.select("div.quote"):
text = card.select_one("span.text")
author = card.select_one("small.author")
if text is None or author is None:
raise ValueError(f"Incomplete quote on {source_url}")
records.append({
"quote": text.get_text(strip=True),
"author": author.get_text(strip=True),
"tags": [tag.get_text(strip=True) for tag in card.select("a.tag")],
"source_url": source_url,
})
if not records:
raise ValueError(f"No quotes found on {source_url}")
return records
def scrape_quotes(max_pages=MAX_PAGES):
if max_pages < 1:
raise ValueError("max_pages must be at least 1")
driver = webdriver.Chrome()
records = []
visited = set()
try:
driver.set_page_load_timeout(30)
wait = WebDriverWait(driver, 20)
driver.get(START_URL)
for page_number in range(1, max_pages + 1):
cards = wait.until(
EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "div.quote"))
)
url = driver.current_url
if url in visited:
raise ValueError(f"Pagination returned to an earlier page: {url}")
visited.add(url)
page_records = extract_quotes(driver.page_source, url)
records.extend(page_records)
print(f"Page {page_number}: collected {len(page_records)} quotes")
if not driver.find_elements(By.CSS_SELECTOR, "li.next a"):
break
if page_number == max_pages:
print(f"Stopped at the {max_pages}-page limit; more pages remain.")
break
old_card = cards[0]
next_link = wait.until(
EC.element_to_be_clickable((By.CSS_SELECTOR, "li.next a"))
)
time.sleep(1) # Pace navigation; the explicit waits detect readiness.
next_link.click()
# This site's Next link replaces the document, so old cards detach.
wait.until(EC.staleness_of(old_card))
# The next loop iteration waits for the new page's visible quotes.
finally:
driver.quit()
return records
if __name__ == "__main__":
quotes = scrape_quotes()
with open("quotes_dynamic.json", "w", encoding="utf-8") as file:
json.dump(quotes, file, ensure_ascii=False, indent=2)
print(f"Saved {len(quotes)} quotes to quotes_dynamic.json")Run it with:
python scrape_dynamic_quotes.pyThe script visits up to three pages and writes quotes_dynamic.json in the current working directory. Each record contains the quote, author, tags and source URL. A successful rerun replaces that file, so rename an earlier export if you want to keep it.
Notice that we extract fields from one div.quote at a time. This keeps each quote paired with its own author. We also find the Next link again on every page, because an element reference from an old document is no longer usable after navigation.
This pagination wait is specific to a page that replaces its document. A single-page application may reuse the same elements and change only their text. In that case, waiting for staleness could time out even though the results changed. Use the interface's active page number, result identifier or loading state to detect completion instead.
Choosing the right approach
Selenium gives us a way to reproduce interactions, but opening a browser also adds work and more things that can change. Before using it on another site, inspect how that site delivers the data.
- If the needed elements are already in the HTTP response, use Requests and BeautifulSoup.
- If an available API provides the data and permits your use, consider requesting that structured response directly.
- If the task depends on browser interaction or JavaScript-rendered elements, use Selenium and explicit waits.
For debugging, keep the browser visible, verify selectors in Inspect, and check what is actually on screen when a wait times out. An empty result might be valid; a timeout might indicate a changed selector or an unfinished login. Increasing every timeout is not a substitute for checking the page.
We have extended the first scraper to handle a browser's changing state: enter information, submit an action, wait for its result and extract the updated content. In Part 3, we can build on this with structured storage, validation, controlled retries and a closer look at APIs used by the page.