簡體   English   中英

滾動直到元素在DOM中

[英]Scroll until element is in DOM

嗨,我正在使用此代碼嘗試滾動頁面,直到元素位於DOM中。 但是,該頁面不會滾動,它只會循環播放。 我的IJavaScriptExecutor錯誤嗎?

public static void ScrollUntilElementinDom(this IWebDriver driver, By by)
{
    bool isPresent = false;
    while (isPresent == false)
    {
        try
        {
            isPresent = driver.FindElement(by).Displayed;
        }
        catch (Exception)
        {

        }
        if (isPresent == true)
        {
            break;
        }
        else
        {
            ((IJavaScriptExecutor) driver).ExecuteScript("window.scrollBy(100,0);");

        }

    }
  • 您正在滾動窗口以觸發更多內容的加載。
  • 您希望繼續滾動窗口,直到加載了您要查找的內容。

您需要等待內容加載

您根本沒有在等。 考慮使用WebDriverWait

嘗試使用Actions滾動

Actions action = new Actions(driver);
action.MoveToElement(driver.FindElement(by)).Build().Perform();

並查找是否顯示該元素,可以使用顯式等待

WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(15));

try
{
    wait.Until(ExpectedConditions.ElementIsVisible(by));
    isPresent = true;
}
catch (Exception) { }

這將等待15秒鍾才能顯示該元素。

您應該使用Actions類來執行到元素的滾動。

WebElement element = driver.findElement(By.id("element-id"));
Actions actions = new Actions(driver);
actions.moveToElement(element);
actions.perform();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM