在 tradingview.com 内找不到带有 Selenium Java 的 Web 元素

Can't find web element with Selenium Java within tradingview.com

我无法在 Java 中使用 Selenium 访问网页的特定元素。

我需要访问 Trading View webpage.

子菜单中的“登录”选项

我尝试了 xPath、CSS 选择器等,但没有任何效果,我猜它在我不知道的网页的某种细分内,但我肯定它不是 <iframe>,我已经检查过了。不过我可能是错的。

我的代码:

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...)
  }
}

你在这里缺少的只是延迟/等待。
在访问之前需要让页面加载你要访问的元素。

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

不会那样做。
您需要在此处使用 Expected Conditions 显式等待:

WebDriverWait wait;

您还需要改进定位器。
这样效果会更好:

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();

}

要单击 登录 元素,首先您需要单击 用户菜单 图标,然后您需要引导 for the and you can use either of the following :

  • 使用 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();
    
  • 使用 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();