有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java NoSuchElementException在heroku上运行,但在本地主机上运行

我有一些奇怪的解析应用程序,可以在localhost上完美运行,但当我将其上传到heroku时,它无法通过xpath找到元素。 它进入带有driver.get("url")(安装了chrome和chromedriver)的页面,我可以在日志currentUrl中看到,但它就是看不到元素

我试过Thread.sleep(n)其中n甚至是120秒,我试过了 WebDriverWait wait = new WebDriverWait(driver, 120);没有什么帮助

代码片段:

options.setBinary("/app/.apt/usr/bin/google-chrome"); 
System.setProperty("webdriver.chrome.driver","/app/.chromedriver/bin/chromedriver");
WebDriver driver = new ChromeDriver(options);
driver.get("https://www.oddsportal.com/results/#soccer");
WebDriverWait wait = new WebDriverWait(driver, 120);

element = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//a[@href='/soccer/austria/tipico-bundesliga/results/']")));
element.click();

当我在本地主机上使用它时,页面会打开,但是

org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element:{"method":"xpath","selector":"//a[@href='/basketball/usa/nba/results/']"}

在heroku的日志中


共 (2) 个答案

  1. # 1 楼答案

    以下是可能解决此问题的几个步骤: 1.检查你是否在正确的页面上。 2.使用检查页面是否已完全加载

    private void WaitUntilDocumentIsReady(TimeSpan timeout)
    {
        JavascriptExecutor js = (JavascriptExecutor)driver;
        var wait = new WebDriverWait(WebDriver, timeout);            
    
        // Check if document is ready
        Func<IWebDriver, bool> readyCondition = webDriver => js.
            .ExecuteScript("return (document.readyState == 'complete' && jQuery.active == 0)");
        wait.Until(readyCondition);
    }
    
    1. 试试Javascript点击js.ExecuteScript("arguments[0].click();", element)
  2. # 2 楼答案

    根据最佳实践,当您的用例要在任何元素上调用click()时,一旦页面在driver.get()而不是presenceOfElementLocated()之后加载,您需要使用ExpectedConditions作为elementToBeClickable()如下:

    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//a[@href='/soccer/austria/tipico-bundesliga/results/']"))).click();