Страница не загружается, поскольку она выбирает текущее местоположение - PullRequest
1 голос
/ 21 апреля 2020

Я пытаюсь автоматизировать приведенный ниже сценарий:

  1. Go на BestBuy.com
  2. Поиск ноутбуков
  3. Нажмите на указанный c ноутбук HP со страницы результатов
  4. Нажмите Добавить в корзину
  5. Нажмите Просмотр корзины
  6. Добавьте почтовый индекс, нажмите кнопку Обновить и нажмите кнопку Продолжить, чтобы оформить заказ
  7. Теперь нажмите на ссылку «Продолжить»
  8. Введите все данные и нажмите «Продолжить»
  9. Введите неверные данные кредитной карты и нажмите «Продолжить»
  10. Подтвердите сообщение об ошибке

Здесь, после шага № 7, он автоматически определяет мое текущее местоположение и добавляет его в URL (например, https://www.bestbuy.ca/checkout/?qit=1# / en-ca / shipping / GJ / 390020), а страница не загружается, которая не удается мой код. Я блокирую веб-сайт, чтобы получить текущее местоположение (через всплывающее окно), но это не помогает. Кто-нибудь может подсказать мне, как решить эту проблему.

Пожалуйста, найдите ниже код:

package seleniumtestingscript;

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;

public class BestBuyScenario {

    WebDriver driver;
    WebDriverWait wait;
    JavascriptExecutor js;
    Select select;

    @BeforeMethod
    public void launch_Browser() {
        System.setProperty("webdriver.chrome.driver", "G:\\Sheetal\\Selenium_Program_Practice\\Driver\\chromedriver.exe");
        driver = new ChromeDriver();
        String URL = "https://www.bestbuy.com/";
        driver.get(URL);
        driver.manage().window().maximize();

    }

    @Test(priority=1)
    public void HappyPath() throws InterruptedException {

    //Click on Canada link
    WebElement Canada_Link = driver.findElement(By.linkText("Canada"));
    Canada_Link.click();

    //wait till search page loads
    wait = new WebDriverWait(driver, 20);
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.name("search")));

    WebElement search_field = driver.findElement(By.xpath("//div/input[@aria-label = 'Search Best Buy']"));
    search_field.clear();
    search_field.sendKeys("Laptops");

    //wait till auto complete list is displayed
    wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//ul/li/a[starts-with(@class,'autocompleteLink')]")));

    //Click on laptops displayed in autocomplete list
    List<WebElement> autocomplete_list = driver.findElements(By.xpath("//ul/li/a[starts-with(@class,'autocompleteLink')]"));
    for(int i = 0; i<autocomplete_list.size(); i++)
    {
        if(autocomplete_list.get(i).getText().contains("laptops"))
        {
            System.out.println(autocomplete_list.get(i).getText());
            autocomplete_list.get(i).click();
            break;

        }
    }
    System.out.println("After loop");
    Thread.sleep(5000);
    //wait till laptop page loads and verify the page title
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div/h1[contains(text(),'Laptops & MacBooks')]")));

    System.out.println("After title on laptop page");
    //Scroll page till HP laptop gets visible and click on that laptop link
    js = (JavascriptExecutor)driver;
    js.executeScript("window.scrollBy(0,1500);", "");
    wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//div[contains(text(),'HP 15.6\" Laptop - Silver (Intel Core i3-1005G1')]"))).click();


    //click on Add to cart button
    Thread.sleep(5000);
    js.executeScript("window.scrollBy(0,150);", "");
    wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//span[contains(text(),'Add to Cart')]"))).click();
    System.out.println("Add to cart clicked");
    //WebElement add_to_cart_button = driver.findElement(By.xpath("//span[contains(text(),'Add to Cart')]"));
    //add_to_cart_button.click();


    //Switch to pop up and click on view cart button

    driver.switchTo().activeElement();
    wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//button[@data-automation='view-cart-confirmation']"))).click();
    //WebElement view_cart_button = driver.findElement(By.xpath("//button[@data-automation='view-cart-confirmation']"));
    //view_cart_button.click();

    wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("postalCode"))).clear();
    WebElement postal_input = driver.findElement(By.id("postalCode"));
    //postal_input.sendKeys(Keys.CONTROL, Keys.chord("a")); //select all text in textbox
    //postal_input.sendKeys(Keys.BACK_SPACE); //delete it
    postal_input.sendKeys("M9V1S3"); //enter new text
    driver.findElement(By.xpath("//button[@data-automation='enter-postal-code-button']")).click();

    //click on continue_to_checkout_button
    js.executeScript("window.scrollBy(0,350);", "");
    wait.until(ExpectedConditions.elementToBeClickable(By.xpath("(//div/div/a[@data-automation='continue-to-checkout'])[position()=2]"))).click();
    //WebElement continue_to_checkout_button = driver.findElement(By.xpath("(//div/div/a[@data-automation='continue-to-checkout'])[position()=2]"));
    //continue_to_checkout_button.click();

    //wait till continue button is displayed and then click on it
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[@data-automation= 'guest-continue']/a")));
    WebElement continue_link = driver.findElement(By.xpath("//div[@data-automation= 'guest-continue']/a"));
    continue_link.click();



    wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("email")));
    WebElement email_field = driver.findElement(By.id("email"));
    email_field.sendKeys("sheetal@test.com");
    WebElement firstName_field = driver.findElement(By.id("firstName"));
    firstName_field.sendKeys("Sheetal");
    js.executeScript("window.scrollBy(0,150);", "");
    WebElement lastName_field = driver.findElement(By.id("lastName"));
    lastName_field.sendKeys("Patel");
    WebElement addressLine_field = driver.findElement(By.id("addressLine"));
    addressLine_field.sendKeys("Etobicoke");
    WebElement city_field = driver.findElement(By.id("city"));
    city_field.sendKeys("Toronto");
    WebElement regionCode_field = driver.findElement(By.id("regionCode"));
    Select select = new Select(regionCode_field);
    select.selectByVisibleText("Ontario");
    WebElement postalCode_field = driver.findElement(By.id("postalCode"));
    postalCode_field.sendKeys("M5G 2C3");
    WebElement phone_field = driver.findElement(By.id("phone"));
    phone_field.sendKeys("8989564646");
    WebElement continue_button = driver.findElement(By.xpath("//span[contains(text(),'Continue')]"));
    continue_button.click();

    WebElement cardnumber_field = driver.findElement(By.id("shownCardNumber"));
    cardnumber_field.sendKeys(card_number);
    WebElement month = driver.findElement(By.id("expirationMonth"));

    select = new Select(month);
    select.selectByVisibleText("1");

    WebElement year = driver.findElement(By.id("expirationYear"));
    select = new Select(year);
    select.selectByVisibleText(card_year);

    WebElement cvv = driver.findElement(By.id("cvv"));
    cvv.sendKeys(card_cvv);

    WebElement continue_button1 = driver.findElement(By.xpath("//span[contains(text(),'Continue')]"));
    continue_button1.click();

    WebElement error_msg = driver.findElement(By.xpath("(//div[@class='error-msg'])[position()=1]"));
    String actual = error_msg.getText();
    String expected = "Invalid credit card number. Please check your credit card number or use another payment method.";
    Assert.assertEquals(actual, expected);


    }





}

1 Ответ

3 голосов
/ 22 апреля 2020

Я нашел решение. Фактическая проблема заключалась в том, что всякий раз, когда я запускал свой сценарий, новый экземпляр браузера разрешал брать текущее местоположение, даже если я заблокировал получение текущего местоположения для этого сайта (щелкните значок блокировки, отображаемый в https://www.bestbuy.com/ url -> Настройки сайта-> Разрешения -> Блокировка местоположения).

Я искал в Google - как всплывающее окно с блокировкой географического местоположения и нашел несколько решений, и ниже работает решение:

    ChromeOptions options = new ChromeOptions();
   Map<String, Object> prefs = new HashMap<String, Object>();
                prefs.put("profile.managed_default_content_settings.geolocation", 2);
options.setExperimentalOption("prefs", prefs);
            driver = new ChromeDriver(options);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...