2 回答
TA贡献1836条经验 获得超5个赞
根据Class URI的 java 文档:
public final class URI
extends Object
implements Comparable<URI>, Serializable
Represents a Uniform Resource Identifier (URI) reference.
URI实例具有以下九个组成部分:
Component Type
-------------------- ------
scheme String
scheme-specific-part String
authority String
user-info String
host String
port int
path String
query String
fragment String
由于您已经通过提取了当前 urlgetCurrentUrl() ,因此您可以将当前 url转换为uri并提取每个组件,如下所示(使用https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/package-summary.html):
代码块:
import java.net.URI;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
public class A_demo
{
public static void main(String[] args) throws URISyntaxException
{
System.setProperty("webdriver.chrome.driver", "C:\\Utility\\BrowserDrivers\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("start-maximized");
WebDriver driver = new ChromeDriver(options);
driver.get("https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/package-summary.html");
String CurrentURL = driver.getCurrentUrl();
URI uri = new URI(CurrentURL);
System.out.println("Scheme: "+uri.getScheme());
System.out.println("Scheme-specific-part: "+uri.getSchemeSpecificPart());
System.out.println("Authority: "+uri.getAuthority());
System.out.println("User-info: "+uri.getUserInfo());
System.out.println("Host: "+uri.getHost());
System.out.println("Port: "+uri.getPort());
System.out.println("Path: "+uri.getScheme());
System.out.println("Query: "+uri.getQuery());
System.out.println("Fragment: "+uri.getFragment());
}
}
控制台输出
Scheme: https
Scheme-specific-part: //seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/package-summary.html
Authority: seleniumhq.github.io
User-info: null
Host: seleniumhq.github.io
Port: -1
Path: https
Query: null
Fragment: null
最后,要构建生成的 URL,https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/WebDriver.html您可以执行以下操作:
driver.navigate().to(uri.getScheme()+"://"+uri.getHost()+"/selenium/docs/api/java/org/openqa/selenium/WebDriver.html");
TA贡献1818条经验 获得超7个赞
document.domain不返回 http/https,例如,它返回该站点的“stackoverflow.com”。
我会用你开始的东西,
String CurrentURL = driver.getCurrentUrl();
将该 URL 转换为 a java.net.URI,然后使用.getHost(). 您可以将这一切包装到类似的方法中
public static String getDomainName(String url) throws URISyntaxException {
URI uri = new URI(url);
String domain = uri.getHost();
return domain.startsWith("www.") ? domain.substring(4) : domain;
}
并称之为
String domainName = getDomainName(driver.getCurrentUrl());
这个答案是我得到该方法的地方,它列出了有关此方法的注意事项,但听起来它可能对您有用。
添加回答
举报