The Wayback Machine - https://web.archive.org/web/20240618234312/https://www.geeksforgeeks.org/scrape-and-save-table-data-in-csv-file-using-selenium-in-python/
Open In App

Scrape and Save Table Data in CSV file using Selenium in Python

Last Updated : 04 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Selenium WebDriver is an open-source API that allows you to interact with a browser in the same way a real user would and its scripts are written in various languages i.e. Python, Java, C#, etc. Here we will be working with python to scrape data from tables on the web and store it as a CSV file. As Google Chrome is the most popular browser, to make things easy, we will be using it. Further to store the data, we will be using the pandas and csv module of python.

Note: Make sure that you have the chromedriver installed in your system and it must be in the same folder as the python file. The chromedriver can be found here.

First, we need to locate the elements of the table, for this selenium WebDriver. We will be using the xpath method as most of the elements in the webpage have a unique xpath. 

Stepwise implementation:

Step 1: Import the required modules. 

Python3




from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support.ui import WebDriverWait
import time
import pandas as pd
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
import csv


Step 2: Initialise the web browser with a variable driver, mention the executable_path as the location where you have the chromedriver file, and direct to the required URL.

Python3




driver = webdriver.Chrome(
  executable_path='/usr/lib/chromium-browser/chromedriver')


Step 3: Wait for the WebPage to load. You can do so by the implicitly_wait(​) method. When fully loaded, maximize the window use maximize_window().

Python3




driver.implicitly_wait(10)
driver.maximize_window()


Step 4: Try to find a pattern in the xpath’s of the rows and locate them using find_element_by_xpath(), and run a loop to find all the table cells and convert them into text by adding .text() at the end of every element located through the generalized xpath.

Python3




while(1):
 
    try:
        method = driver.find_element(By.XPATH, '//*[@id="post-427949"]\
        /div[3]/table[2]/tbody/tr['+str(r)+']/td[1]').text
        Desc = driver.find_element(By.XPATH, '//*[@id="post-427949"]\
        /div[3]/table[2]/tbody/tr['+str(r)+']/td[2]').text
        Table_dict = {
            'Method': method,
            'Description': Desc
        }
        templist.append(Table_dict)
        df = pd.DataFrame(templist)
        r += 1
 
    except NoSuchElementException:
        break


Step 5: Export the Dataframe to a CSV file and close the exit of the browser.

Python3




df.to_csv('table.csv')
driver.close()


Below is the complete implementation:

Python3




from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support.ui import WebDriverWait
import time
import pandas as pd
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
import csv
 
driver = webdriver.Chrome(
    executable_path='/usr/lib/chromium-browser/chromedriver')
 
driver.implicitly_wait(10)
driver.maximize_window()
r = 1
templist = []
 
while(1):
    try:
        method = driver.find_element(By.XPATH, '//*[@id="post-427949"]\
        /div[3]/table[2]/tbody/tr['+str(r)+']/td[1]').text
        Desc = driver.find_element(By.XPATH, '//*[@id="post-427949"]/\
        div[3]/table[2]/tbody/tr['+str(r)+']/td[2]').text
 
        Table_dict = {'Method': method,
                      'Description': Desc}
 
        templist.append(Table_dict)
        df = pd.DataFrame(templist)
 
        r + = 1
 
    # if there are no more table data to scrape
    except NoSuchElementException:
        break
 
# saving the dataframe to a csv
df.to_csv('table.csv')
driver.close()


Output:



Previous Article
Next Article

Similar Reads

Scrape IMDB movie rating and details using Python and saving the details of top movies to .csv file
We can scrape the IMDb movie ratings and their details with the help of the BeautifulSoup library of Python. Modules Needed: Below is the list of modules required to scrape from IMDB. requests: Requests library is an integral part of Python for making HTTP requests to a specified URL. Whether it be REST APIs or Web Scraping, requests must be learne
4 min read
Scrape LinkedIn Using Selenium And Beautiful Soup in Python
In this article, we are going to scrape LinkedIn using Selenium and Beautiful Soup libraries in Python. First of all, we need to install some libraries. Execute the following commands in the terminal. pip install selenium pip install beautifulsoup4In order to use selenium, we also need a web driver. You can download the web driver of either Interne
7 min read
Scrape a popup using python and selenium
Web scraping is the process of extracting data from websites. It involves programmatically accessing web pages, parsing the HTML or XML content, and extracting the desired information. With the help of libraries like BeautifulSoup, Selenium, or Scrapy in Python, web scraping can be done efficiently. It enables automating data collection, scraping p
3 min read
How to scrape multiple pages using Selenium in Python?
As we know, selenium is a web-based automation tool that helps us to automate browsers. Selenium is an Open-Source testing tool which means we can easily download it from the internet and use it. With the help of Selenium, we can also scrap the data from the webpages. Here, In this article, we are going to discuss how to scrap multiple pages using
4 min read
NumPy save() Method | Save Array to a File
The NumPy save() method is used to store the input array in a binary file with the 'npy extension' (.npy). Example: C/C++ Code import numpy as np a = np.arange(5) np.save('array_file', a) SyntaxSyntax: numpy.save(file, arr, allow_pickle=True, fix_imports=True) Parameters: file: File or filename to which the data is saved. If the file is a string or
2 min read
How to save a Python Dictionary to a CSV File?
Prerequisites: Working with csv files in Python CSV (comma-separated values) files are one of the easiest ways to transfer data in form of string especially to any spreadsheet program like Microsoft Excel or Google spreadsheet. In this article, we will see how to save a PYthon dictionary to a CSV file. Follow the below steps for the same. Import cs
2 min read
Save API data into CSV format using Python
In this article, we are going to see how can we fetch data from API and make a CSV file of it, and then we can perform various stuff on it like applying machine learning model data analysis, etc. Sometimes we want to fetch data from our Database Api and train our machine learning model and it was very real-time by applying this method we can train
6 min read
How to create multiple CSV files from existing CSV file using Pandas ?
In this article, we will learn how to create multiple CSV files from existing CSV file using Pandas. When we enter our code into production, we will need to deal with editing our data files. Due to the large size of the data file, we will encounter more problems, so we divided this file into some small files based on some criteria like splitting in
3 min read
Save image properties to CSV using Python
In this article, we are going to write python scripts to find the height, width, no. of channels in a given image file and save it into CSV format. Below is the implementation for the same using Python3. The prerequisite of this topic is that you have already installed NumPy and OpenCV. Approach: First, we will load the required libraries into the
3 min read
How to save file with file name from user using Python?
Prerequisites: File Handling in PythonReading and Writing to text files in Python Saving a file with the user's custom name can be achieved using python file handling concepts. Python provides inbuilt functions for working with files. The file can be saved with the user preferred name by creating a new file, renaming the existing file, making a cop
5 min read
Practice Tags :