0

I want to know how can copy the "?ned=us&topic=t" part in "http://news.google.com/?ned=us&topic=t". Basically, I want to copy the path of the url, or the portion after the ".com". How do I do this?

public class Example  {
public static String url = "http://news.google.com/?ned=us&topic=t";
    public static void main(String[] args) {
        WebDriver driver = new FirefoxDriver();
            driver.get(url);
            WebElement reportCln=driver.findElement(By.id("id_submit_button"));
            String path=driver.getCurrentUrl();
            System.out.println(path);
}
}

3 Answers 3

3

You should have a look at the java.net.URL class and its getPath() and getQuery() methods.

@Test
public void urls() throws MalformedURLException {
    final URL url = new URL("http://news.google.com/?ned=us&topic=t");

    assertEquals("ned=us&topic=t", url.getQuery());
    assertEquals("?ned=us&topic=t", "?" + url.getQuery());
    assertEquals("/", url.getPath());
}

Regular expressions are fun, but IMO this is easier to understand.

Sign up to request clarification or add additional context in comments.

1 Comment

This is by far the best answer. You don't have to worry about case sensitivity, you don't have to worry about invalid URL's and there is no cleverness involved. IMHO the KISS(Keep It Simple Stupid) approach is always the best.
1

Try this:

String request_uri = null;
String url = "http://news.google.com/?ned=us&topic=t";

if (url.startsWith("http://") {
    request_uri = url.substring(7).split("/")[1];
} else {
    request_uri = url.split("/")[1];
}

System.out.println (request_uri); // prints: ?ned=us&topic=t

If you're only interested in the query string i.e. for google.com/search?q=key+words you want to ignore search? then just split on ? directly

// prints: q=key+words
System.out.println ("google.com/search?q=key+words".split("\\?")[0]);

Comments

1

You can use regular expression to extract the part you want:

String txt = "http://news.google.com/?ned=us&topic=t";

String re1 = "(http:\\/\\/news\\.google\\.com\\/)"; // unwanted part
String re2 = "(\\?.*)"; // wanted part

Pattern p = Pattern.compile(re1 + re2, Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
Matcher m = p.matcher(txt);
if (m.find())
{
    String query = m.group(2);
    System.out.print(query);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.