- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWebScrape.java
More file actions
Latest commit
38 lines (28 loc) · 1.86 KB
/
Copy pathWebScrape.java
File metadata and controls
38 lines (28 loc) · 1.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
importorg.jsoup.nodes.*;
importorg.jsoup.*;
publicclassWebScrape {
publicstaticvoidmain(String[] args) {
inttotal = 0; //Variable to store total number of cases
Stack<String> myStack = newStack<String>(); //Stack to store all the data of date and cases
Stringcountry = args[0]; //First user-entered argument specifies the country
intdays = Integer.parseInt(args[1]); //Second user-entered argument specifies the number of days
finalStringurl = "https://www.google.com/search?q="+country+"+corona+cases"; //URL to search
try {
finalDocumentmyDoc = Jsoup.connect(url).get();
for (Elementlist : myDoc.select("div.FMJSFf ol li")) { //Select all the elements beginning with <li> inside <ol> under div class='FMJSFf'
myStack.push(list.toString().replace("<li>", "").replace("</li>","")); //Removes <li>and</li> from results obtained and push it into stack
}
if (days > myStack.size())
days = myStack.size();
System.out.println("\nListed below is the number of new cases each day in "+country+" for the past "+days+" days:");
for (inti=0; i < days; i++) { //Pops x entry from the stack, returning the cases each day and accumulates total cases
Stringdata = myStack.pop();
System.out.println(data); //Prints out 'numberOfCases on date'
total += Integer.parseInt((data.split(" on ")[0]).replaceAll(",","")); //Data obtained is in the form 'numberOfCases on date', hence split the string to {numberOfCases, date} and convert numberOfCases to Integer
}
System.out.println("The total number of cases for the past "+days+" days is "+total+".");
} catch(Exceptionex) {
ex.printStackTrace();
}
}
}