Search code examples
javaapiseleniumoauth-2.0automation

How to Extract particular String from Output console or output text file using Selenium with Java


I have printed the network logs for a website as output in console (Selenium with Java) and trying to extract the Authorization Bearer Token from the console. Output is large and trying to extract only the Auth bearer.

I tried to put the output in the txt file and extract but the whole line is extracting not the particular auth bearer. How to get it?

I have stored the logs in txt file and trying to fetch by below.

public class BufferedReaderExample {

    public static void main(String args[])throws Exception
    {
        // BufferedReader br = new BufferedReader(new FileReader("ModellerOutput.txt"));
        LineNumberReader reader=  new LineNumberReader(new FileReader("E:\\consoledata.txt"));

        String line;
        while ((line = reader.readLine()) != null) 
        {
            if(line.contains("Bearer"))
            {
                System.out.println(reader.getLineNumber());
                // for(int i=reader.getLineNumber();i<=(reader.getLineNumber()+50);i++)
               // {
                //   System.out.println(reader.getLineNumber());
                String line1 = Files.readAllLines(Paths.get("E:\\consoledata.txt")).get(reader.getLineNumber());
                   
                //   System.out.println(line1.startsWith("Bearer"));//true  
                 //  System.out.println(line1.endsWith(","));
                   System.out.println(line1); 
            }   
        }
    }
}
{"webview":"92072A77A4E7CE70B654162022145D0A",
"message":{"method":"Network.requestWillBeSent",
"params":{"request":{"headers":{"Authorization":"Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6Ilg1ZVhrNHh5b2pORnVtMWtsMll0djhkbE5QNC1jNTdkTzZRR1RWQndhTmsifQ.eyJleHAiOjE2MjQ5NzAyNTAsIm5iZiI6MTYyNDk2NjY1MCwidmVyIjoiMS4wIiwiaXNzIjoiaHR0cHM6Ly90ZWxzdHJhc21hcnRzcGFjZXNiMmNkZXYuYjJjbG9naW4uY29tL2M4OTJmNmExLTZjZjEtNDJlNi04YWQ5LTAyMzUwNTJmYzc0NS92Mi4wLyIsInN1YiI6IjZlNjVhOTE4LTU4NmUtNDQ4ZC1iZjVhLTk1OGJmNzBmOWQ5NSIsImF1ZCI6IjE4MWZlOWU2LWUyYWYtNGFhYi04OTgwLWI2Zjk2OTExYWQzNiIsIm5vbmNlIjoiM2ZkZjQ0MjUtMTNhNS00MWYxLThhZDItYjczMDdjNDY4MmFkIiwiaWF0IjoxNjI0OTY2NjUwLCJhdXRoX3RpbWUiOjE2MjQ5NjY2NTAsImlkcCI6Imh0dHBzOi8vc2EudGh5cmEudGVsc3RyYS5jb20vU2VjdXJlQXV0aDU4NyIsImdpdmVuX25hbWUiOiJHYXVyYXYiLCJmYW1pbHlfbmFtZSI6IlNyaXZhc3RhdmEiLCJuYW1lIjoiU3JpdmFzdGF2YSwgR2F1cmF2Iiwib2lkIjoiNmU2NWE5MTgtNTg2ZS00NDhkLWJmNWEtOTU4YmY3MGY5ZDk1IiwidGZwIjoiQjJDXzFfbXl3b3JrcGxhY2Vfd2ViYXBwIn0.kpqB7mfgxp8oNpga7AciHanayHdJOQDcjT9zDhQDYHmLl-bkWjVQfhJQvwm5K94kFiarlDTkRBjabtD3h0we_D1DR8Wmq1t7qm2a52vUqNjBeNN23rn0ST56MgqiFTa9VITVmURxscXz38ZFCciTO7JCaO1Yj_bhRCcMBeFDvV8Dr-f9y563iTeu6BagRJjHwF_70N961DD_HqIkEAIB775RUkq5YouYuqBg-4zMUqRFXYdax0iKm7gEnFzqRq78DDlVNnyEKJEVyGyykUp4yhBsAYo7qIEk8OhrVwlvC0mTLmhisBtRjCM5K5lrv9ePcF0E6kHrSlIIRyHBKLtDYQ",
"sec-ch-ua":"\" Not;A Brand\";v=\"99\", \"Google Chrome\";v=\"91\", \"Chromium\";v=\"91\"","sec-ch-ua-mobile":"?0","Accept":"application/json, text/plain, 


Solution

  • The text you're trying to process looks like it's in JSON format.

    Method 1: Use a JSON parser

    The cleanest way is to parse the text with a JSON parser (e.g. GSON). Then you can navigate the data object and extract the piece you want.

    Method 2: Use a regular expression

    Alternatively, you could use a regular expression to extract the part you're interested in. This approach would be a bit of a hack, but that might not matter for your situation. Something like this:

    String s = "{\"webview\":\"92072A77A4E7CE70B654162022145D0A\",\n"
            + "\"message\":{\"method\":\"Network.requestWillBeSent\",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_HqIkEAIB775RUkq5YouYuqBg-4zMUqRFXYdax0iKm7gEnFzqRq78DDlVNnyEKJEVyGyykUp4yhBsAYo7qIEk8OhrVwlvC0mTLmhisBtRjCM5K5lrv9ePcF0E6kHrSlIIRyHBKLtDYQ\",\n"
            + "\"sec-ch-ua\":\"\\\" Not;A Brand\\\";v=\\\"99\\\", \\\"Google Chrome\\\";v=\\\"91\\\", \\\"Chromium\\\";v=\\\"91\\\"\",\"sec-ch-ua-mobile\":\"?0\",\"Accept\":\"application/json, text/plain, \n"
            + "";
    Pattern bearerPattern = Pattern.compile("\"Bearer ([^\"]+)\"");
    Matcher matcher = bearerPattern.matcher(s);
    matcher.find();
    String token = matcher.group(1);
    System.out.println(token);
    

    Prints:

    eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6Ilg1ZVhrNHh5b2pORnVtMWtsMll0djhkbE5QNC1jNTdkTzZRR1 ... lIIRyHBKLtDYQ

    Method 3: Use indexOf and substring

    Or, similar to Gautham's answer, you could use indexOf and substring:

    String prefix = "Bearer ";
    int i = s.indexOf(prefix);
    String token = s.substring(i + prefix.length(), s.indexOf("\"", i));
    

    This differs slightly from Gautham's answer in that it uses indexOf(String str, int fromIndex) to find the position of the quote, which avoids the need to perform substring twice.