nbhgt
nbhgt

Reputation: 37

Java How to copy part of a url in webdriver?

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);
}
}

Upvotes: 0

Views: 3537

Answers (3)

Simon Arsenault
Simon Arsenault

Reputation: 1845

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);
}

Upvotes: 1

Spiff
Spiff

Reputation: 2286

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.

Upvotes: 3

Ravi K Thapliyal
Ravi K Thapliyal

Reputation: 51711

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]);

Upvotes: 1

Related Questions