Last updated: November 18, 2026
To scrape a table in Python, use pandas.read_html() when the table is a well-formed HTML table in the page source, requests with BeautifulSoup when you need control over individual rows and cells, and Selenium or Playwright when JavaScript loads the table after the page opens. Check the page source or network requests first: if the data is in the HTML or a JSON response, you rarely need a browser.
Table scraping is the process of locating an HTML table on a web page, reading its rows and columns, and converting them into a structured format such as a pandas DataFrame or CSV file.
Data is growing faster than ever, and tables are often the most organized form of information on websites. Whether it is product pricing, stock market updates, research statistics, or government data, accessing this information efficiently can save time and improve decision-making. Python has become the go-to language for web scraping because of its simplicity, flexibility, and powerful libraries.
This guide covers how to scrape tables in Python, from beginner-friendly static tables to advanced dynamic tables loaded with JavaScript. You will also learn how to clean and structure your scraped data, automate recurring scraping tasks, and explore real-world use cases. By the end of this guide, you will have the knowledge to extract reliable table data and integrate it into your workflow.
Last reviewed: November 18, 2026. The code in this guide has not been re-tested for this update, so test it on your own setup before you rely on it. For Python scraping in general, see how to scrape data with Python, Python scraping best practices and Python libraries for web extraction.
Which Tool Should You Use? A Quick Comparison
| Tool / Library | Best for | Needs a browser? | Handles JavaScript | Handles merged cells | Learning curve |
|---|---|---|---|---|---|
| pandas.read_html | Quick extraction from well-formed tables | No | No | Limited | Low |
| BeautifulSoup (with Requests) | Static tables and custom parsing | No | No | Yes, with extra code | Low to medium |
| Selenium | Tables loaded by JavaScript | Yes | Yes | Yes, with extra code | Medium |
| Playwright | Tables loaded by JavaScript | Yes | Yes | Yes, with extra code | Medium |
| Managed service | Ongoing, larger-scale collection | No, handled for you | Yes | Depends on scope | Low for you |
Check each library’s current documentation for exact capabilities.
What Do You Need to Know Before Scraping a Table?
What is Web Scraping?
Web scraping is the process of extracting data from websites. Unlike downloading files or using an API, scraping involves fetching the web page content, parsing it, and extracting the information you need. For table data, this means identifying HTML elements that represent rows and columns and converting them into a usable format, such as a pandas DataFrame or CSV file.
Is It Legal to Scrape Tables From a Website?
Whether you can scrape a table depends on the site’s terms, the data and your jurisdiction, so check the site’s robots.txt file and terms of service. The Ninth Circuit addressed scraping of publicly available data under the Computer Fraud and Abuse Act in hiQ Labs v. LinkedIn (9th Cir. 2022), and a site’s terms of service are a separate matter (White & Case’s summary of website terms and the CFAA); RFC 9309 states that robots.txt rules are not a form of access authorization. See is web scraping legal?
Which Python Libraries Can Scrape Tables?
- BeautifulSoup – Ideal for parsing HTML and extracting data from static pages.
- pandas – Provides
read_html()to extract tables quickly into DataFrames. - Selenium – Controls a web browser to scrape dynamic content loaded via JavaScript.
- Playwright – Another modern tool for scraping dynamic websites efficiently.
- Requests – Used to fetch HTML content directly before parsing.
How Do You Scrape a Static HTML Table in Python?
Before you run the code below: the URL is a placeholder, library versions are not stated, and you should check the site’s robots.txt and terms first. A developer should confirm versions and a tested date before this is relied on.
Static tables are those fully loaded when the page opens. These are easier to scrape because no JavaScript rendering is required.
Step 1: Inspect the Table
How Do You Tell If a Table Is Static or JavaScript-Loaded?
View the page source. If the table’s rows appear there, it is static. If the source is empty but Inspect shows the table, JavaScript loads it. You can also check the browser’s network calls for a JSON response that holds the data.
Open the web page in your browser, right-click on the table, and select “Inspect” to find the HTML structure. Look for <table>, <tr> (rows), and <td> or <th> (columns).
Step 2: Extract Table with BeautifulSoup
import requests
from bs4 import BeautifulSoup
import pandas as pd
url = "https://example.com/sample-table"
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
table = soup.find('table')
rows = table.find_all('tr')
data = []
for row in rows:
cols = row.find_all(['td', 'th'])
cols = [ele.text.strip() for ele in cols]
data.append(cols)
df = pd.DataFrame(data[1:], columns=data[0])
print(df)
This code fetches the table, parses it, and converts it into a pandas DataFrame. You can then save it to CSV or Excel.
Handling Nested or Merged Cells
Some tables have cells that span multiple rows or columns. You can handle this by carefully parsing rowspan and colspan attributes in BeautifulSoup and expanding them to match the table structure.
How Do You Scrape a JavaScript-Loaded Table?
Dynamic tables are loaded with JavaScript, meaning the HTML source does not include the data until it executes scripts.
Using Selenium
Selenium automates browsers and can interact with dynamic content:
from selenium import webdriver
from selenium.webdriver.common.by import By
import pandas as pd
import time
driver = webdriver.Chrome()
driver.get("https://example.com/dynamic-table")
time.sleep(3) # Wait for table to load
table = driver.find_element(By.TAG_NAME, "table")
rows = table.find_elements(By.TAG_NAME, "tr")
data = []
for row in rows:
cols = row.find_elements(By.TAG_NAME, "td")
cols = [ele.text for ele in cols]
data.append(cols)
df = pd.DataFrame(data)
driver.quit()
print(df)
Using Playwright
Playwright is a newer browser automation tool with support for headless browsers. See Selenium and Playwright in enterprise scraping.
from playwright.sync_api import sync_playwright
import pandas as pd
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page()
page.goto("https://example.com/dynamic-table")
page.wait_for_selector("table")
table = page.query_selector("table")
rows = table.query_selector_all("tr")
data = []
for row in rows:
cols = [col.inner_text() for col in row.query_selector_all("td")]
data.append(cols)
df = pd.DataFrame(data)
browser.close()
print(df)
Can pandas.read_html() Scrape a Table in One Line?
If the table is properly structured, pandas’ read_html() can extract it directly:
import pandas as pd
url = "https://example.com/sample-table"
tables = pd.read_html(url)
df = tables[0] # Select the first table
print(df)
This is ideal for quick extraction, especially for static tables, and integrates smoothly into your Python data pipeline.
How Do You Automate Table Scraping on a Schedule?
Automation saves time and ensures data is always up-to-date. You can schedule scripts with cron jobs or Python’s schedule library:
import schedule
import time
def scrape_table():
# Your scraping code here
print("Scraping table...")
schedule.every().day.at("09:00").do(scrape_table)
while True:
schedule.run_pending()
time.sleep(60)
For ongoing, larger-scale needs, a managed service can run scheduled pipelines with monitoring and error handling. See Python web scraping vs enterprise data extraction and speeding up Python web scrapers.
How Do You Save Scraped Table Data to CSV or Excel?
Once the table is in a pandas DataFrame, write it out with the DataFrame’s CSV or Excel export methods. Use the same DataFrame from the static or dynamic steps above. A developer should confirm the exact export call for your pandas version.
What Are Common Table Scraping Use Cases?
Example 1: E-commerce Pricing Table
Scraping product prices weekly to track competitor pricing can be automated and stored in a database for analysis.
Example 2: Stock Market Tables
Financial analysts extract stock market tables daily to feed trading models or dashboards.
Example 3: Academic Research Data
Researchers scrape tables from journals or public databases for statistical analysis.
These examples demonstrate the range of use cases from small-scale scripts to enterprise-level automation.
Which Tool Should You Use to Scrape Tables?
Best Practices
- Always check
robots.txtbefore scraping. - Avoid overwhelming the server with too many requests. Use rate limiting.
- If a site limits automated requests, slow down or look for an official API or data source.
- Structure your data for downstream analysis.
- Maintain logs for troubleshooting and auditing.
Why Is My Table Scraper Missing Rows or Data?
- Missing rows or columns: Check HTML structure; some cells may be nested.
- Dynamic content not loading: Ensure your browser automation waits for tables to render.
- AJAX tables: Investigate network requests; sometimes API endpoints can be used directly.
- Data type inconsistencies: Clean the data in pandas using appropriate transformations.
- Blocking: If a site limits automated requests, check its terms and look for an official API. See anti-bot defenses and headless browsers.
FAQs
Can I scrape tables from any website using Python?
Not always. Check the site’s terms of service and robots.txt. Some sites restrict scraping. The Ninth Circuit addressed scraping of publicly available data under the Computer Fraud and Abuse Act in hiQ Labs v. LinkedIn (9th Cir. 2022), and a site’s terms of service are a separate matter (White & Case’s summary of website terms and the CFAA); RFC 9309 states that robots.txt rules are not a form of access authorization.
Should I use BeautifulSoup, Selenium or Playwright for tables?
Use BeautifulSoup for static tables. For tables loaded by JavaScript, use Selenium or Playwright. Check the page source first, because many tables do not need a browser.
How do I handle tables loaded via JavaScript?
Use Selenium or Playwright to render the page, or check the network calls, because some tables can be fetched from a JSON endpoint the page uses.
How do I scrape a table with pandas read_html?
Pass the page URL to pandas.read_html(). It returns a list of DataFrames, one for each table it finds, and you select the one you need.
How do I save a scraped table to CSV or Excel?
Convert the table to a pandas DataFrame, then use its CSV or Excel export methods.
Why does read_html return no tables?
Common causes are a table loaded by JavaScript, a page that blocks the request, or markup that is not a standard HTML table. Check the page source to see which applies.
How can I automate scraping so data stays up-to-date?
Use cron jobs or Python’s schedule library. For larger-scale needs, a managed service can run scheduled pipelines with monitoring.
How do I clean and structure scraped table data?
Pandas can remove empty rows and columns, rename headers, convert data types and remove unwanted characters.
When Should You Move Beyond Python Scripts?
Web scraping tables in Python allows you to extract valuable data efficiently and integrate it into your workflows. By starting with static tables, exploring dynamic table scraping, and learning to clean and automate your data pipelines, you can save time and unlock insights from publicly available sources.
When Python stops being enough, such as many sites, frequent layout changes or the need for monitoring, a managed service can take over extraction, cleaning and delivery. See the web scraping solution and the web scraping API.
Start small with Python scripts and explore automation as your needs grow.