使用Selenium WebDriver自动化时如何阻止URL自动跳转?
问题描述
- 访问
https://www.lambdatest.com/时,系统自动跳转到https://www.lambdatest.com/pricing页面,导致测试用例失败,即使使用无痕模式,跳转仍会发生。 - 无法连接Selenium Grid,所有测试用例均被跳过,存在2项配置失败。
相关代码与配置
Java测试代码
public class TestScenario { WebDriver driver; JavascriptExecutor js; String currentWindow; @BeforeClass @Parameters({ "browser", "browserVersion", "platform" }) public void setUp(String browser, String browserVersion, String platform) { String username = "XXXXXX"; String accessKey = "XXXXXX"; /* * HashMap<String, Object> ltOptions = new HashMap<String, Object>(); // * ltOptions.put("username", "XXXXXX"); * ltOptions.put("accessKey", * "XXXXX"); * ltOptions.put("visual", true); ltOptions.put("video", true); * ltOptions.put("network", true); ltOptions.put("build", "Build 0.1"); * ltOptions.put("project", "Selenium Advanced"); ltOptions.put("name", * "Retest"); ltOptions.put("tunnel", true); ltOptions.put("w3c", true); * ltOptions.put("plugin", "java-testNG"); * * if (browser.equalsIgnoreCase("chrome")) { ChromeOptions browserOptions = new * ChromeOptions(); * * browserOptions.setPlatformName(platform); * browserOptions.setBrowserVersion(browserVersion); * browserOptions.setCapability("LT:Options", ltOptions); * * try { driver = new RemoteWebDriver( new URL("https://" + username + ":" + * accessKey + "@hub.lambdatest.com/wd/hub"), browserOptions); * * } catch (MalformedURLException e) { // TODO Auto-generated catch block * e.printStackTrace(); } driver.manage().window().maximize(); * driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(20)); * * } else if (browser.equalsIgnoreCase("MicrosoftEdge")) { * * EdgeOptions browserOptions = new EdgeOptions(); * * browserOptions.setPlatformName(platform); * browserOptions.setBrowserVersion(browserVersion); * browserOptions.setCapability("LT:Options", ltOptions); * * try { driver = new RemoteWebDriver( new URL("https://" + username + ":" + * accessKey + "@hub.lambdatest.com/wd/hub"), browserOptions); * * } catch (MalformedURLException e) { // TODO Auto-generated catch block * e.printStackTrace(); } driver.manage().window().maximize(); * driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(20)); * * } else { throw new IllegalArgumentException("Invalid browser name: " + * browser); } */ if (browser.equalsIgnoreCase("chrome")) { driver = new ChromeDriver(); driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(20)); } else if (browser.equalsIgnoreCase("MicrosoftEdge")) { driver = new EdgeDriver(); driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(20)); } } @Test(priority = 1) public void testcase1() { /* * 1. Navigate to https://www.lambdatest.com/. */ driver.get("https://www.lambdatest.com/"); /* * 2. Perform an explicit wait till the time all the elements in the DOM are * available. 3. Scroll to the WebElement ‘SEE ALL INTEGRATIONS’ using the * scrollIntoView() method. You are free to use any of the available web * locators (e.g., XPath, CssSelector, etc.) */ WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(20)); wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.xpath("//*"))); WebElement seeAllIntegrations = driver.findElement(By.linkText("SEE ALL INTEGRATIONS")); js = (JavascriptExecutor) driver; js.executeScript("arguments[0].scrollIntoView(true);", seeAllIntegrations); /* * 4. Click on the link and ensure that it opens in a new Tab. * * 5. Save the window handles in a List (or array). Print the window handles of * the opened windows (now there are two windows open). */ currentWindow = driver.getWindowHandle(); Actions ac = new Actions(driver); ac.moveToElement(seeAllIntegrations).contextClick().build().perform(); ac.sendKeys(Keys.DOWN, Keys.ENTER).build().perform(); Set<String> allOpenedWindows = driver.getWindowHandles(); wait.until(ExpectedConditions.numberOfWindowsToBe(2)); List<String> handles = new ArrayList<String>(allOpenedWindows); for (String child : handles) { if (!currentWindow.equals(child)) driver.switchTo().window(child); } /* * 6. Verify whether the URL is the same as the expected URL (if not, throw an * Assert). */ String expectedUrl = "https://www.lambdatest.com/integrations"; Assert.assertEquals(driver.getCurrentUrl(), expectedUrl, "URL is not the same as expected."); } @Test(priority = 2) public void testcase2() { /* * 7. On that page, scroll to the page where the WebElement (Codeless * Automation) is present. */ WebElement codelessAutomation = driver .findElement(By.xpath("//*[@id=\"__next\"]/div[1]/section[2]/div/div/div[1]/div/ul/li[5]/a")); codelessAutomation.click(); js.executeScript("arguments[0].scrollIntoView(true);", codelessAutomation); /* * 8. Click the ‘LEARN MORE’ link for Testing Whiz. The page should open in the * same window. */ WebElement learnMore = driver.findElement(By.xpath("//*[@id=\"codeless_row\"]/div/div[4]/a")); learnMore.click(); /* * 9. Check if the title of the page is ‘TestingWhiz Integration | * LambdaTest’.If not, raise an Assert. */ String expectedTitle = "TestingWhiz Integration | LambdaTest"; Assert.assertEquals(driver.getTitle(), expectedTitle, "Title is not as expected."); /* * 10. Close the current window using the window handle [which we obtained in * step (5)] */ driver.close(); driver.switchTo().window(currentWindow); int currentWindowCount = driver.getWindowHandles().size(); System.out.println("Current window count: " + currentWindowCount); } @Test(priority = 3) public void testCase3() { /* * 12. On the current window, set the URL to https://www.lambdatest.com/blog. * 13. Click on the ‘Community’ link and verify whether the URL is * https://community.lambdatest.com/. 14. Close the current browser window. */ driver.get("https://www.lambdatest.com/blog"); driver.findElement(By.xpath("//*[@id=\"menu-item-10121\"]/a")).click(); String expectedUrl = "https://community.lambdatest.com/"; Assert.assertEquals(driver.getCurrentUrl(), expectedUrl, "URL is not the same as expected."); driver.close(); } @AfterClass public void tearDown() { driver.quit(); } }
TestNG配置文件
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd"> <suite name="LambdaTest Suite" parallel="classes" thread-count="2"> <test name="Test Scenario 1"> <parameter name="browser" value="chrome" /> <parameter name="browserVersion" value="86.0" /> <parameter name="platform" value="Windows 10" /> <classes> <class name="seleniumAdvanced_Assignment.TestScenario" /> </classes> </test> <test name="Test Scenario 2"> <parameter name="browser" value="MicrosoftEdge" /> <parameter name="browserVersion" value="87.0" /> <parameter name="platform" value="macOS Sierra" /> <classes> <class name="seleniumAdvanced_Assignment.TestScenario" /> </classes> </test> </suite>
错误日志
[RemoteTestNG] detected TestNG version 7.8.0 SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". SLF4J: Defaulting to no-operation (NOP) logger implementation SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details. Jul 30, 2023 3:07:39 PM org.openqa.selenium.remote.tracing.opentelemetry.OpenTelemetryTracer createTracer INFO: Using OpenTelemetry for tracing =============================================== LambdaTest Suite Total tests run: 6, Passes: 0, Failures: 0, Skips: 6 Configuration Failures: 2, Skips: 2 ===============================================
内容的提问来源于stack exchange,提问作者Ezhumalai Shanmugam
相关产品推荐
相关产品推荐

