Remove word from string java – Java Program to Delete a Word from Sentence

Remove word from string java: Want to excel in java coding? Practice with these Java Programs examples with output and write any kind of easy or difficult programs in the java language

Java Program to Delete a Word from Sentence

  • Java program to delete a word from sentence using replaceAll() method.

In this java program, we have to remove a word from a string using replaceAll method of String class. Deleting a word from a sentence is a two step process, first you have to search the word the given sentence. Then you have to delete all characters of word from string and shift the characters to fill the gap in sentence.
For Example,
Input Sentence : I love Java Programming
Word to Delete : Java
Output Sentence : I love Programming

Java program to delete a word from a sentence

In this program, we will use replaceAll() method of String class, which replaces the each occurrence of given word in sentence with “”. Hence deleting the word from sentence.
Java program to delete a word from a sentence

package com.tcc.java.programs;
 
import java.util.Scanner;
 
/**
 * Java Program to Delete Vowels from String
 */
public class DeleteWordFromSentence {
    public static void main(String args[]) {
        String sentence, word;
        Scanner scanner = new Scanner(System.in);
 
        System.out.println("Enter a Sentence");
        sentence = scanner.nextLine();
 
        System.out.println("Enter word you want to delete from Sentence");
        word = scanner.nextLine();
        // Deleting word from
        sentence = sentence.replaceAll(word, "");
 
        System.out.println("Output Sentence\n" + sentence);
    }
}

Output

I love Java Programming
Enter word you want to delete from Sentence
Java
Output Sentence
I love  Programming

Java program to calculate grades – Java Program to Calculate Grade of Students

Java program to calculate grades: Access the Simple Java program for Interview examples with output from our page and impress your interviewer panel with your coding skills.

Java Program to Calculate Grade of Students

  • Java Program to find the grade of a student, given the marks of N subjects.

Given the marks of N subjects, we have to print the grade of a student based on the following grade slab.

  • If Percentage Marks > 90, Grade is A+
  • If 70 <= Percentage Marks <= 89, Grade is A
  • If 60 <= Percentage Marks <= 69, Grade is B
  • If 50 <= Percentage Marks <= 59, Grade is C
  • If Percentage Marks <= 40, Grade is D

In this java program, we first ask user to enter number of subjects and store it in variable “count”. Then using a for loop, we take marks of “count” subjects as input from user and add them to variable “totalMarks”. Then we find the percentage marks of student using following expression assuming each subject is of 100 marks.

percentage = (totalMarks/(count*100)) * 100;
Using a switch case, we check the grade of the student as per the slab mentioned above and print it on screen.

Java program to calculate the grade of a student

Java program to calculate the grade of a student

package com.tcc.java.programs;
 
import java.util.Scanner;
 
/**
 * Java Program to print grade of a student
 */
public class StudentGrade {
    public static void main(String[] args) {
        int count, i;
        float totalMarks = 0, percentage, average;
        Scanner scanner;
        scanner = new Scanner(System.in);
 
        System.out.println("Enter Number of Subject");
        count = scanner.nextInt();
 
        System.out.println("Enter Marks of " + count + " Subject");
        for (i = 0; i < count; i++) {
            totalMarks += scanner.nextInt();
        }
        System.out.println("Total MArks : " + totalMarks);
        // Each subject is of 100 Marks
        percentage = (totalMarks / (count * 100)) * 100;
 
        /* Printing grade of a student using switch case statement */
        switch ((int) percentage / 10) {
        case 9:
            System.out.println("Grade : A+");
            break;
        case 8:
        case 7:
            System.out.println("Grade : A");
            break;
        case 6:
            System.out.println("Grade : B");
            break;
        case 5:
            System.out.println("Grade : C");
            break;
        default:
            System.out.println("Grade : D");
            break;
        }
    }
}

Output

Enter Number of Subject
5
Enter Marks of 5 Subject
45 69 53 58 62
Total MArks : 287.0
Grade : C

Standard deviation c++ – C++ Program to Calculate Standard Deviation

Standard deviation c++: In the previous article, we have discussed C++ Program to Find Quotient and Remainder. In this article, we will see C++ Program to Calculate Standard Deviation.

C++ Program to Calculate Standard Deviation

  • Write a C++ program to calculate standard deviation.

In this C++ program, we will calculate standard deviation of N numbers stored in an array. Standard Deviation in statistics is a measure that is used to quantify the amount of variation in a set of data. Its symbol is σ (greek letter sigma) is used to represent standard deviation.

C++ Program to Calculate Standard Deviation

C++ Program to Calculate Standard Deviation

#include <iostream>
#include <cmath>
using namespace std;
 
float findStandardDeviation(float *array, int count);
 
int main() {
    int count, i;
    float inputArray[500];
     
    cout << "Enter number of elements\n";
    cin >> count;
     
    cout << "Enter " << count <<" elements\n";
    for(i = 0; i < count; i++){
     cin >> inputArray[i];
    }
 
    cout << "Standard Deviation = " << findStandardDeviation(inputArray, count);
 
    return 0;
}
// Function to find standard deviation 
float findStandardDeviation(float *array, int count) {
    float sum = 0.0, sDeviation = 0.0, mean;
    int i;
 
    for(i = 0; i < count; i++) {
        sum += array[i];
    }
    // Calculating mean 
    mean = sum/count;
 
    for(i = 0; i < count; ++i) {
        sDeviation += pow(array[i] - mean, 2);
    }
 
    return sqrt(sDeviation/count);
}

Output

Enter number of elements
10
Enter 10 elements
2 4 5 6 8 9 10 13 14 16
Standard Deviation = 4.36005

In above program, we first take N numbers as input from user and store it in an integer array “inputArray”. Here we have created a function “findStandardDeviation” calculates and return the value of standard.

If you are a newbie to the programming languages and want to explore all Example C++ Program for acquiring the best coding skills. Have a look at our C++ Programs Tutorial.

Prime number in c++ using function – C++ Program to Check Prime Number Using Function

Prime number in c++ using function: In the previous article, we have discussed C++ Program to Check Prime Number. In this article, we will see C++ Program to Check Prime Number Using Function.

C++ Program to Check Prime Number Using Function

  • Write a C++ program to check whether a number is prime number or not using function.

In this program, we will learn about prime numbers and how to check whether a number is prime number or not. Here s the formal definition of prime numbers:

Prime number is a natural number greater than 1 that is only divisible by either 1 or itself. In other words, a prime is not divisible by any other number other than itself. All numbers other than prime numbers are known as composite numbers.

First few prime numbers are : 2 3 5 7 11 13 17 19 23 29 …

C++ program to check a prime number using function

C++ program to check a prime number using function

// C++ program to check prime number
#include <iostream>
using namespace std;
  
bool isPrimeNumber(int num);
 
int main() {
  int num;
  cout << "Enter a positive number\n";
  cin >> num;
    
  if(isPrimeNumber(num))
      cout << num << " is a Prime Number";
  else
      cout << num << " is NOT a Prime Number";
        
  return 0;
}
 
bool isPrimeNumber(int num){
  bool isPrime = true;
  int i;
  // Check whether num is divisible by any number between 2 to (num/2)
  for(i = 2; i <=(num/2); ++i) {
      if(num%i==0) {
          isPrime=false;
          break;
      }
  }
 
  return isPrime;
}

Output

Enter a positive number
13 
13 is a Prime Number
Enter a positive number
15 
15 is NOT a Prime Number

In this program, we first take an integer as input from user using cin and store it in a variable num. We then call isPrimeNumber function by passing num to check whether num is prime number or not.

Here we defined a function isPrimeNumber which check whether a number is prime number or not. If number is prime then it returns true otherwise false. To test whether a number is prime or not we are using brute force approach by testing whether num is a multiple of any integer between 2 and num/2. If num is divisible by any number between 2 and num/2 then num is not a prime number.

This is the most basic method of checking the primality of a given integer num and is called trial division.

Finally, based on the return value of isPrimeNumber function, we display message on screen saying whether number is prime number or not.

Start writing code in C++ language by referring to Simple C++ Program Examples available here. These examples are helpful to get an idea on the format, function used in every basic program.

Bar() in c – C Program to Draw a Rectangle and Bar Using C Graphics

Write a program in C to draw a rectangle and a bar on screen using graphics.h header file

Bar() in c: In this program, we will draw a rectangle and a bar on screen. We will use rectangle and bar functions of graphics.h header file to draw rectangle and bar on screen. Below is the detailed descriptions if these two functions.

void rectangle(int xTopLeft, int yTopLeft, int xBottomRight, int yBottomRight);

rectangle function draws a rectangle on screen. It takes the coordinates of top left and bottom right corners.

void bar(int xTopLeft, int yTopLeft, int xBottomRight, int yBottomRight);

bar function draws a rectangle and fill it with current fill pattern and color.

Function Argument Description
xTopLeft X coordinate of top left corner.
yTopLeft Y coordinate of top left corner.
xBottomRight X coordinate of bottom right corner.
yBottomRight Y coordinate of bottom right corner.

C program to draw rectangle and bar using graphics

C Program to Draw a Rectangle and Bar Using C Graphics

#include<stdio.h>
#include<graphics.h>
#include<conio.h>
 
int main(){
   int gd = DETECT,gm;
   initgraph(&gd, &gm, "C:\\TC\\BGI");
 
   /* Draw rectangle on screen */
   rectangle(150, 50, 400, 150);
 
   /* Draw Bar on screen */
   bar(150, 200, 400, 350);
 
   getch();
   closegraph();
   return 0;
}

Program Output

RECTANGLE

Simple calculator program in java using switch case – Java Program to Make a Simple Calculator using Switch Case

Simple calculator program in java using switch case: If you are new to Java and want to learn the java coding skills too fast. Try practicing the core java programs with the help of the Java basic programs list available.

Java Program to Make a Simple Calculator using Switch Case

  • Write a Java program to make a simple calculator using switch case statement which perform addition, subtraction, multiplication and division or two numbers.

Given two integers and an arithmetic operator, we have to perform the specific arithmetic operation on given integer operands using a switch case statement and print the result on screen.

Java program for simple calculator using switch statement

In this java program, we first takes two integer operands and an arithmetic operator as input from user. The operator is stored in a character variable ‘op’. This calculator only support addition, subtraction, multiplication and division(+, – , * and /) operators and for any other operator it prints error message on screen saying “Unsupported Operation”. It uses switch case statement to select an arithmetic operation based on the ‘op’ variable.

Java program for simple calculator using switch statement

package com.tcc.java.programs;
 
import java.util.Scanner;
 
/**
 * Java Program to Make a Simple Calculator using Switch Statement
 */
public class Calculator {
    public static void main(String[] args) throws myException {
        int a, b;
        char op;
 
        Scanner scanner;
        scanner = new Scanner(System.in);
        // Take two numbers as input from user
        System.out.println("Enter Two Integers");
        a = scanner.nextInt();
        b = scanner.nextInt();
 
        // Taking operator as input from user
        System.out.println("Enter an Operator");
        op = scanner.next().charAt(0);
 
        switch (op) {
        case '+':
            System.out.format("%d + %d = %d\n", a, b, a + b);
            break;
        case '-':
            System.out.format("%d - %d = %d\n", a, b, a - b);
            break;
        case '*':
            System.out.format("%d * %d = %d\n", a, b, a * b);
            break;
        case '/':
            System.out.format("%d / %d = %d\n", a, b, a / b);
            break;
        default:
            System.out.println("ERROR: Unsupported Operation");
        }
    }
}

Output

Enter Two Integers
10 4
Enter an Operator
+
10 + 4 = 14
Enter Two Integers
4 7
Enter an Operator
*
4 * 7 = 28
Enter Two Integers
2 3
Enter an Operator
^
ERROR: Unsupported Operation

Python get last digit of int – C Program to Find Sum of First and Last Digits of a Number

C Program to Find Sum of First and Last Digits of a Number
  • Write a C program to find sum of first and last digits of a number.
  • Wap in C to find sum of least significant and most significant digit of a number.

Required Knowledge

Python get last digit of int: To get the least significant digit of a number we will use ‘%’ modulus operator. Number%10 will give the least significant digit of the number. Then we will remove one digit at a time form number using below mentioned algorithm and then store the most significant digit in firstDigit variable.
Sum of first and last digits of 2534 = 2 + 4 = 6

Algorithm to find first and last digits of a number

  • Get least significant digit of number (number%10) and store it in lastDigit variable.
  • Remove least significant digit form number (number = number/10).
  • Repeat above two steps, till number is greater than 10.
  • The remaining number is the first digit of number.

C program to find sum of first and last digits of a number

C Program to Find Sum of First and Last Digits of a Number

#include <stdio.h>
 
int main() {  
    int num, temp, firstDigit, lastDigit;  
   
    /* 
     * Take a number as input from user
     */ 
    printf("Enter a Number\n"); 
    scanf("%d", &num);  
    temp = num;
     
    /* get last digit of num */
    lastDigit = num %10;
     
    while(num > 10){
        /* Keep on removing the last digit untill 
         num becomes less than 10(single digit) */
        num = num/10;
    } 
    firstDigit = num;
    printf("Sum of first and last digit of %d = %d", temp, firstDigit+lastDigit);  
   
    getch();
    return 0;  
}

Output

Enter a Number
2436
Sum of first and last digit of 2436 = 8
Enter a Number
2222
Sum of first and last digit of 2222 = 4

Write a C program to find product of digits of a number using while loop.
Wap in C to multiply the digits of a number.

Required Knowledge

  • C printf and scanf functions
  • While loop in C

To multiply digits of a number we have to remove one digit at a time, we can use ‘/’ division and ‘%’ modulus operator. Number%10 will give the least significant digit of the number, we will use it to get one digit of number at a time. To remove last least significant digit from number we will divide number by 10.

Product of digits of 2534 = 2 x 5 x 3 x 4 = 120

Algorithm to find product of digits of a number

  • Get least significant digit of number (number%10) and multiply it to the product variable.
  • Remove least significant digit form number (number = number/10).
  • Repeat above two steps, till number is not equal to zero.

C program to find sum of all even numbers between 1 to N using for loop

C program to find sum of all even numbers between 1 to N using for loop 1

#include <stdio.h>
#include <conio.h>  
   
int main() {  
    int num, temp;  
    long productOfDigit = 1;  
   
    /* 
     * Take a number as input from user
     */ 
    printf("Enter a Number\n");  
    scanf("%d", &num);  
    temp = num;
     
    while(num != 0){
        /* get the least significant digit(last digit) 
         of number and multiply it to productofDigit */
        productOfDigit *= num % 10;
        /* remove least significant digit(last digit)
         form number */
        num = num/10;
    } 
   
    printf("Product of digits of %d = %ld", temp, productOfDigit);  
   
    getch();
    return 0;  
}

Output

Enter a Number
2436
Product of digits of 2436 = 144
Enter a Number
2222
Product of digits of 2436 = 16

How To Scrape LinkedIn Public Company Data – Beginners Guide

How To Scrape LinkedIn Public Company Data

Nowadays everybody is familiar with how big the LinkedIn community is. LinkedIn is one of the largest professional social networking sites in the world which holds a wealth of information about industry insights, data on professionals, and job data.

Now, the only way to get the entire data out of LinkedIn is through Web Scraping.

Why Scrape LinkedIn public data?

There are multiple reasons why one wants to scrape the data out of LinkedIn. The scrape data can be useful when you are associated with the project or for hiring multiple people based on their profile while looking at their data and selecting among them who all are applicable and fits for the company best.

This scraping task will be less time-consuming and will automate the process of searching for millions of data in a single file which will make the task easy.

Another benefit of scraping is when one wants to automate their job search. As every online site has thousands of job openings for different kinds of jobs, so it must be hectic for people who are looking for a job in their field only. So scraping can help them automate their job search by applying filters and extracting all the information at only one page.

In this tutorial, we will be scraping the data from LinkedIn using Python.

Prerequisites:

In this tutorial, we will use basic Python programming as well as some python packages- LXML and requests.

But first, you need to install the following things:

  1. Python accessible here (https://www.python.org/downloads/)
  2. Python requests accessible here(http://docs.python-requests.org/en/master/user/install/)
  3. Python LXML( Study how to install it here: http://lxml.de/installation.html)

Once you are done with installing here, we will write the python code to extract the LinkedIn public data from company pages.

This below code will only run on python 2 and not above them because the sys function is not supported in it.

import json

import re

from importlib import reload

import lxml.html

import requests

import sys

reload(sys)

sys.setdefaultencoding('cp1251')




HEADERS = {'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',

          'accept-encoding': 'gzip, deflate, sdch',

          'accept-language': 'en-US,en;q=0.8',

          'upgrade-insecure-requests': '1',

          'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36'}

file = open('company_data.json', 'w')

file.write('[')

file.close()

COUNT = 0




def increment():

   global COUNT

   COUNT = COUNT+1




def fetch_request(url):

   try:

       fetch_url = requests.get(url, headers=HEADERS)

   except:

       try:

           fetch_url = requests.get(url, headers=HEADERS)

       except:

           try:

               fetch_url = requests.get(url, headers=HEADERS)

           except:

               fetch_url = ''

   return fetch_url




def parse_company_urls(company_url):




   if company_url:

       if '/company/' in company_url:

           parse_company_data(company_url)

       else:

           parent_url = company_url

           fetch_company_url=fetch_request(company_url)

           if fetch_company_url:

               sel = lxml.html.fromstring(fetch_company_url.content)

               COMPANIES_XPATH = '//div[@class="section last"]/div/ul/li/a/@href'

               companies_urls = sel.xpath(COMPANIES_XPATH)

               if companies_urls:

                   if '/company/' in companies_urls[0]:

                       print('Parsing From Category ', parent_url)

                       print('-------------------------------------------------------------------------------------')

                   for company_url in companies_urls:

                       parse_company_urls(company_url)

           else:

               pass







def parse_company_data(company_data_url):




   if company_data_url:

       fetch_company_data = fetch_request(company_data_url)

       if fetch_company_data.status_code == 200:

           try:

               source = fetch_company_data.content.decode('utf-8')

               sel = lxml.html.fromstring(source)

               # CODE_XPATH = '//code[@id="stream-promo-top-bar-embed-id-content"]'

               # code_text = sel.xpath(CODE_XPATH).re(r'<!--(.*)-->')

               code_text = sel.get_element_by_id(

                   'stream-promo-top-bar-embed-id-content')

               if len(code_text) > 0:

                   code_text = str(code_text[0])

                   code_text = re.findall(r'<!--(.*)-->', str(code_text))

                   code_text = code_text[0].strip() if code_text else '{}'

                   json_data = json.loads(code_text)

                   if json_data.get('squareLogo', ''):

                       company_pic = 'https://media.licdn.com/mpr/mpr/shrink_200_200' + \

                                     json_data.get('squareLogo', '')

                   elif json_data.get('legacyLogo', ''):

                       company_pic = 'https://media.licdn.com/media' + \

                                     json_data.get('legacyLogo', '')

                   else:

                       company_pic = ''

                   company_name = json_data.get('companyName', '')

                   followers = str(json_data.get('followerCount', ''))




                   # CODE_XPATH = '//code[@id="stream-about-section-embed-id-content"]'

                   # code_text = sel.xpath(CODE_XPATH).re(r'<!--(.*)-->')

                   code_text = sel.get_element_by_id(

                       'stream-about-section-embed-id-content')

               if len(code_text) > 0:

                   code_text = str(code_text[0]).encode('utf-8')

                   code_text = re.findall(r'<!--(.*)-->', str(code_text))

                   code_text = code_text[0].strip() if code_text else '{}'

                   json_data = json.loads(code_text)

                   company_industry = json_data.get('industry', '')

                   item = {'company_name': str(company_name.encode('utf-8')),

                           'followers': str(followers),

                           'company_industry': str(company_industry.encode('utf-8')),

                           'logo_url': str(company_pic),

                           'url': str(company_data_url.encode('utf-8')), }

                   increment()

                   print(item)

                   file = open('company_data.json', 'a')

                   file.write(str(item)+',\n')

                   file.close()

           except:

               pass

       else:

           pass
fetch_company_dir = fetch_request('https://www.linkedin.com/directory/companies/')

if fetch_company_dir:

   print('Starting Company Url Scraping')

   print('-----------------------------')

   sel = lxml.html.fromstring(fetch_company_dir.content)

   SUB_PAGES_XPATH = '//div[@class="bucket-list-container"]/ol/li/a/@href'

   sub_pages = sel.xpath(SUB_PAGES_XPATH)

   print('Company Category URL list')

   print('--------------------------')

   print(sub_pages)

   if sub_pages:

       for sub_page in sub_pages:

           parse_company_urls(sub_page)

else:

   pass

How to Code a Scraping Bot with Selenium and Python

How to Code a Scraping Bot with Selenium and Python

Selenium is a powerful tool for controlling web browsers through programs and performing browser automation. Selenium is also used in python for scraping the data. It is also useful for interacting with the page before collecting the data, this is the case that we will discuss in this article.

In this article, we will be scraping the investing.com to extract the historical data of dollar exchange rates against one or more currencies.

There are other tools in python by which we can extract the financial information. However, here we want to explore how selenium helps with data extraction.

The Website we are going to Scrape:

Understanding of the website is the initial step before moving on to further things.

Website consists of historical data for the exchange rate of dollars against euros.

In this page, we will find a table in which we can set the date range which we want.

That is the thing which we will be using.

We only want the currencies exchange rate against the dollar. If that’s not the case then replace the “usd” in the URL.

The Scraper’s Code:

The initial step is starting with the imports from the selenium, the Sleep function to pause the code for some time and the pandas to manipulate the data whenever necessary.

How to Code a Scraping Bot with Selenium and Python

Now, we will write the scraping function. The function will consists of:

  • A list of currency codes.
  • A start date.
  • An End date.
  • A boolean function to export the data into .csv file. We will be using False as a default.

We want to make a scraper that scrapes the data about the multiple currencies. We also have to initialise the empty list to store the scraped data.

How to Code a Scraping Bot with Selenium and Python 1

As we can see that the function has the list of currencies and our plan is to iterate over this list and get the data.

For each currency we will create a URL, instantiate the driver object, and we will get the page by using it.

Then the window function will be maximized but it will only be visible when we will keep the option.headless as False.

Otherwise, all the work will be done by the selenium without even showing you.

How to Code a Scraping Bot with Selenium and Python 2

Now, we want to get the data for any time period.

Selenium provides some awesome functionalities for getting connected to the website.

We will click on the date and fill the start date and end dates with the dates we want and then we will hit apply.

We will use WebDriverWait, ExpectedConditions, and By to make sure that the driver will wait for the elements we want to interact with.

The waiting time is 20 seconds, but it is to you whichever the way you want to set it.

We have to select the date button and it’s XPath.

The same process will be followed by the start_bar, end_bar, and apply_button.

The start_date field will take in the date from which we want the data.

End_bar will select the date till which we want the data.

When we will be done with this, then the apply_button will come into work.

How to Code a Scraping Bot with Selenium and Python 3

Now, we will use the pandas.read_html file to get all the content of the page. The source code of the page will be revealed and then finally we will quit the driver.

How to Code a Scraping Bot with Selenium and Python 4

How to handle Exceptions In Selenium:

The collecting data process is done. But selenium is sometimes a little unstable and fail to perform the function we are performing here.

To prevent this we have to put the code in the try and except block so that every time it faces any problem the except block will be executed.

So, the code will be like:

for currency in currencies:

        while True:

            try:

                # Opening the connection and grabbing the page

                my_url = f'https://br.investing.com/currencies/usd-{currency.lower()}-historical-data'

                option = Options()

                option.headless = False

                driver = webdriver.Chrome(options=option)

                driver.get(my_url)

                driver.maximize_window()

                  

                # Clicking on the date button

                date_button = WebDriverWait(driver, 20).until(

                            EC.element_to_be_clickable((By.XPATH,

                            "/html/body/div[5]/section/div[8]/div[3]/div/div[2]/span")))

               

                date_button.click()

               

                # Sending the start date

                start_bar = WebDriverWait(driver, 20).until(

                            EC.element_to_be_clickable((By.XPATH,

                            "/html/body/div[7]/div[1]/input[1]")))

                           

                start_bar.clear()

                start_bar.send_keys(start)




                # Sending the end date

                end_bar = WebDriverWait(driver, 20).until(

                            EC.element_to_be_clickable((By.XPATH,

                            "/html/body/div[7]/div[1]/input[2]")))

                           

                end_bar.clear()

                end_bar.send_keys(end)

              

                # Clicking on the apply button

                apply_button = WebDriverWait(driver,20).until(

                      EC.element_to_be_clickable((By.XPATH,

                      "/html/body/div[7]/div[5]/a")))

               

                apply_button.click()

                sleep(5)

               

                # Getting the tables on the page and quiting

                dataframes = pd.read_html(driver.page_source)

                driver.quit()

                print(f'{currency} scraped.')

                break

           

            except:

                driver.quit()

                print(f'Failed to scrape {currency}. Trying again in 30 seconds.')

                sleep(30)

                Continue

For each DataFrame in this dataframes list, we will check if the name matches, Now we will append this dataframe to the list we assigned in the beginning.

Then we will need to export a csv file. This will be the last step and then we will be over with the extraction.

How to Code a Scraping Bot with Selenium and Python 5

Wrapping up:

This is all about extracting the data from the website.So far this code gets the historical data of the exchange rate of a list of currencies against the dollar and returns a list of DataFrames and several .csv files.

https://www.investing.com/currencies/usd-eur-historical-data