C# Selenium - Finding Element On Continuously Growing Page

ε祈祈猫儿з 提交于 2019-11-28 05:36:56

问题


I am trying to find a better way to do this than using:

js.ExecuteScript("scroll(0, 1300)");

I have a page where the data can change making the page height change up or down in size. So when I go to click on an element today that is located at 1500px, tomorrow it may be 800px and the element will not be found and the test case fails.

So what have you guys used to locate elements on a page where the size changes?


回答1:


I am not sure if this will work but you can try getting the max height of your page using something like this:

Math.max($(document).height(), $(window).height())

Then you can scroll using js.ExecuteScript.

I'd still use findElement after that to initate the click.




回答2:


I am going to take @ratsstack's answer little further and make it little easier for you to implement. I am not sure if there is a cleaner way to do this. But, at least something that should work. You can provide an estimated number of scroll you think is sufficient for the page to load fully. Notice you can provide more number than you think is correct. It does not really hurt or will not cause your script to fail.

public void ScrollPage(int counter)
{
    const string script =
        @"window.scrollTo(0,Math.max(document.documentElement.scrollHeight,document.body.scrollHeight,document.documentElement.clientHeight));";


    int count = 0;

    while (count != counter)
    {
       IJavaScriptExecutor js = _driver as IJavaScriptExecutor;
        js.ExecuteScript(script);

        Thread.Sleep(500);

        count++;
    }
}

Note: I am using Thread.Sleep() to give the page sometime to finish loading. However, it is never recommanded to use hardcoded use. I am not sure about the technolgies you are using so really cannot provide any wait mechanism to wait for the page load. You can use something and replace the Thread.Sleep()

Implementation

ScrollPage(8);



回答3:


I started using the below which seems to be working nicely. Thanks for the help all.

           IWebElement bio = SeleniumDriver.FindElement(By.XPath("path"));
                Actions actions = new Actions(SeleniumDriver);
                actions.MoveToElement(bio);
                actions.Perform();


来源:https://stackoverflow.com/questions/28662524/c-sharp-selenium-finding-element-on-continuously-growing-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!