本文主要是介绍Java+Selenium3方法篇17-获取当前页面URL,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
本篇介绍获取当前页面的url,这个getCurrentUrl()是一个driver的方法,返回的当前driver所停留在的当前页的url。这个在自动化测试过程中是有必要的,例如在实际测试中,只会刚开始给一个测试url,开始测试,之后的其他页面,都是通过点击链接进行跳转的,所以,有时候需要判断新跳转的链接是不是正确的地址,这个时候就需要获取当前地址拿过来进行断言测试。
实例:百度首页点击新闻这个链接,跳转后,验证新闻的url是不是http://news.baidu.com
相关脚本代码如下:
package lessons;import java.util.concurrent.TimeUnit;import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;public class ElementOpration {public static void main(String[] args) throws Exception { System.setProperty("webdriver.chrome.driver", ".\\Tools\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);driver.get("https://www.baidu.com"); Thread.sleep(2000);String title = driver.getTitle();System.out.println(title);WebElement news_link = driver.findElement(By.linkText("新闻"));news_link.click();Thread.sleep(1000);String current_url = driver.getCurrentUrl();assert current_url == "http://news.baidu.com";}
}
这里需要记住getCurrentUrl()是获取当前网页的URL之外,还需要学会先定义一个WebElement对象,然后通过element.方法名称()的方式去进行元素相关操作。之前我们都是从driver.findElement(By.id("xxx")).元素相关方法()来进行操作,以后建议写成本文这样的写法,脚本看起来更加清晰,高效。
这篇关于Java+Selenium3方法篇17-获取当前页面URL的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!