0

I can't access a specific element of a webpage with Selenium in Java.

I need to access the "sign in" option inside of a submenu of the Trading View webpage.

I tried xPath, CSS selector, etc. but nothing works, I guess it's inside some kind of subdivision of the webpage I don't know, but I'm positive it's not an <iframe>, I have already checked that. I could be wrong though.

The element I need to access

My code:

public class Main {
  public static void main(String[] args){

      System.setProperty("webdriver.opera.driver","C:\\Documents\\LIBRARIES\\Opera Driver\\operadriver.exe");
      WebDriver driver = new OperaDriver();
      driver.get("https://www.tradingview.com");
      driver.manage().timeouts().scriptTimeout(Duration.ofSeconds(4));
      driver.findElement(By.xpath(("/html/body/div[2]/div[3]/div[2]/div[3]/button[1]"))).click();
      driver.manage().timeouts().scriptTimeout(Duration.ofSeconds(4));
     // This is where I need to select the element of the webpage, nothing works so far (Xpath, CSS, ID...)
  }
}
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352

2 Answers2

0

All you missing here is a delay / wait.
You need to let page loaded the element you are going to access before accessing it.

driver.manage().timeouts().scriptTimeout(Duration.ofSeconds(4));

Will not do that.
You need to use Expected Conditions explicit wait here:

WebDriverWait wait;

Also you need to improve your locator.
This would work better:

public class Main {
public static void main(String[] args){
    System.setProperty("webdriver.opera.driver","C:\\Documents\\LIBRARIES\\Opera Driver\\operadriver.exe");

    WebDriver driver = new OperaDriver();
    WebDriverWait wait = new WebDriverWait(driver, 30);

    driver.get("https://www.tradingview.com");
    
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//button[contains(@class,'user-menu-button--anonymous')]"))).click();

}
Prophet
  • 32,350
  • 22
  • 54
  • 79
0

To click on the Sign in element first you need to click on the user menu icon and then you need to induce WebDriverWait for the elementToBeClickable() and you can use either of the following locator strategies:

  • Using cssSelector:

    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("button[aria-label='Open user menu']"))).click();
    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("div[data-name='header-user-menu-sign-in'] div[class^='label'] div[class^='label']"))).click();
    
  • Using xpath:

    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//button[@aria-label='Open user menu']"))).click();
    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//div[text()='Sign in']"))).click();
    
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352