Home > Back-end >  How to click on the href tag?
How to click on the href tag?

Time:09-21

I have DOM

<div class="" data-zone-data="{"id":"97017425"}"data-zone-name="category-link">
<div class="_35SYu _1vnug" data-tid="acbe4a11 f8542ee1">
<a href="/catalog--kompiuternaia-tekhnika/54425" class="_3Lwc_">
<span class="_3z8Gf">Компьютеры</span>
</a>
</div>
</div>
enter code here

Constructor:

   public YandexBeforeSearch(WebDriver driver, String search){
        this.driver = driver;
        this.driver.get("https://yandex.ru/search?text="   search);

    }

My methods:

    public void clickToSite(){
        LinkYandexMarket = driver.findElement(By.xpath("//a[@accesskey='1']"));
        LinkYandexMarket.click();
    }
    public void clickTYandexPC(){
        LinkYandexPC = driver.findElement(By.xpath("//a[@href='/catalog--kompiuternaia-tekhnika/54425']"));
        LinkYandexPC.click();
    }

My test:

@Test
public void testOpen(){
    YandexBeforeSearch yandexBeforeSearch = new YandexBeforeSearch(chromeDriver, "yandex market");
    yandexBeforeSearch.clickToSite();
    yandexBeforeSearch.clickTYandexPC();
}

Exception:

org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//a[@href='catalog--kompiuternaia-tekhnika/54425']"}

I also used other attributes. The problem occurs only with this site. I can't follow the link to the category.

CodePudding user response:

When the 1st link //a[@accesskey='1'] is clicked a new window is opened.

We need to switch to that new window to click on //a[@href='/catalog--kompiuternaia-tekhnika/54425']

// Click on the 1st link.
driver.findElement(By.xpath("//a[@accesskey='1']")).click();

// Get parent window.
String parentwindow = driver.getWindowHandle();

// Get all window handles.
Set<String> windows = driver.getWindowHandles();
List<String> windows1 = new ArrayList<>(windows);

// Switch to the new window to click on the other link.
driver.switchTo().window(windows1.get(1));
driver.findElement(By.xpath("//a[@href='/catalog--kompiuternaia-tekhnika/54425']")).click();

// Switch back to parent window, if required.
driver.switchTo().window(parentwindow);
  • Related