Created
July 9, 2018 14:06
-
-
Save atechcrew/40a5344d6615e4db33866674f53cc0e1 to your computer and use it in GitHub Desktop.
Get google search results using java. Java code to get google search results. Track google rank using java. Google Rank Tracker in java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.IOException; | |
import java.util.ArrayList; | |
import java.util.List; | |
import org.jsoup.Jsoup; | |
import org.jsoup.nodes.Document; | |
import org.jsoup.nodes.Element; | |
import org.jsoup.select.Elements; | |
public class GoogleSearch { | |
static List<String> titles = new ArrayList<String>(); | |
static List<String> urls = new ArrayList<String>(); | |
public static void main(String args[]) { | |
getDataFromGoogle("snooker"); | |
for(int i = 0; i < titles.size(); i++) { | |
System.out.println(titles.get(i)); | |
System.out.println(urls.get(i)); | |
System.out.println(); | |
} | |
} | |
private static void getDataFromGoogle(String query) { | |
int number_of_results = 10; | |
String request = "https://www.google.com.pk/search?q=" + query + "&num=" + number_of_results; | |
try { | |
Document doc = Jsoup.connect(request).userAgent("chrome") | |
.timeout(90000).get(); | |
Elements elements = doc.getElementsByClass("r"); | |
for(Element element : elements) { | |
String title = element.child(0).text(); | |
String url = element.child(0).attr("href"); | |
titles.add(title); | |
urls.add(refineUrl(url)); | |
} | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
public static String refineUrl(String url) { | |
url = url.replaceAll("/url\\?q=", ""); | |
url = url.substring(0, url.indexOf("&sa")); | |
return url; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment