Selenium WebDriver - 如何处理Ajax调用

3

我一直在研究如何在Selenium webdriver中处理AJAX。有很多解决方案,但是否存在一个最好且正确的解决方案呢?

目前为止我看到的解决方案有:

1) 使用线程休眠 2) waitFor方法 3) ExpectedCondition 4) FluentWait 5) PresenceOfElementLocated

谢谢!

4个回答

0
如果你正在使用jQuery,这是我的建议。你可以精确控制轮询的频率。
// poll every 1/3 second for 3 seconds
int timeout = 3; // seconds
int pollFreq = 3; // times per second

WebDriverWait wait = new WebDriverWait(driver, timeout, 1000/pollFreq);
// to be safe, test (driver instanceof JavascriptExecutor) here
JavascriptExecutor executor = ((JavascriptExecutor) driver);

// Check to see if jQuery is available first
Boolean hasJquery = (Boolean) executor.executeScript("return !!window.jQuery");
Boolean hasActive = (Boolean) executor.executeScript("return typeof window.jQuery.active === \"number\"");
if (hasJquery && hasActive) {
    // Wait for JS AJAX calls to complete...
    wait.until((ExpectedCondition<Boolean>) driver -> (Boolean) executor
            .executeScript("return window.jQuery.active === 0"));
    // JS AJAX calls completed.
    // Good idea to add a timing report here for troubleshooting.
}
// else jQuery/active-prop not available, continue

0
处理ajax组件(例如在我的情况下使用)的可靠解决方案是使用webdriver的waitUntil() API调用等待元素在页面上可见。
否则,像threadsleep()这样的解决方案根本不推荐用于处理Ajax。

0

我已经使用过这个,它本身等待的功能很好。

driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

谢谢,试一下。


-1
如果您想从测试中执行ajax请求,您可能需要尝试使用Apache Http Client。以下是一些Groovy代码,可以实现此功能。您可能不会使用Groovy,但这仍然对客户端中的Get和Post有一定的参考价值。
import groovy.util.Expando
import org.apache.commons.httpclient.HttpClient
import org.apache.commons.httpclient.HttpStatus
import org.apache.commons.httpclient.methods.PostMethod
import org.apache.commons.httpclient.methods.GetMethod
import java.io.BufferedReader
import java.io.InputStreamReader
import org.apache.commons.httpclient.Header
import java.net.URLDecoder
import com.auto.utils.crypto.Crypto

class ClientHttps {
private HttpClient client = null
private BufferedReader br = null
private String cookieString = ""
private crypto = new Crypto()
def log
public ClientHttps(log) {
    this.log = log
    client = new HttpClient();
    client.getParams().setParameter("http.useragent", "Mozilla/5.0 (Windows NT 6.1; rv:10.0.2) Gecko/20100101 Firefox/10.0.2")
}
public Expando get(String url) {
    def startTime = System.nanoTime()
    GetMethod method = new GetMethod(url)
    Expando returnData = new Expando()
    try {
        log.info("cookieString = " + cookieString)
        method.addRequestHeader("Cookie", cookieString)
        method.addRequestHeader("Accept", "application/json")
        int returnCode = client.executeMethod(method)
        log.info("returnCode = " + returnCode)
        if (returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {
            log.error("The Get method is not implemented by this URI")
        } else {
            if ((returnCode != HttpStatus.SC_OK) && (returnCode != HttpStatus.SC_MOVED_PERMANENTLY))
                assert false, "Bad Response Code"
            br = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()))
            String readLine;
            while(((readLine = br.readLine()) != null)) {
                log.info(readLine)
            }
            Header [] respHeaders = method.getResponseHeaders()
            respHeaders.each () {
                log.info(it.getName() + " = " + it.getValue())
                returnData.setProperty(it.getName(), it.getValue())
            }
        }
        def endTime = System.nanoTime()
        def duration = endTime - startTime;
        def seconds = (double)duration / 1000000000.0;
        log.info("Get took = " + seconds + " seconds (Get url = " + url + ")")
        return returnData;
    } catch (Exception e) {
        log.error(e.message, e)
        return null
    } finally {
        method.releaseConnection()
        if(br != null) try {
            br.close()
        } catch (Exception fe) {
            log.info(fe.message, fe)
        }
    }
}
public Expando post(Expando postData) {
    def startTime = System.nanoTime()
    PostMethod method = new PostMethod(postData.getProperty("url"))
    postData.getProperty("params").each() {method.addParameter(it.key, it.value)}
    Expando returnData = new Expando()
    try {
        int returnCode = client.executeMethod(method)
        log.info(returnCode)
        if(returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {
            log.error("The Post method is not implemented by this URI")
        } else {
            if ((returnCode != HttpStatus.SC_OK) && (returnCode != HttpStatus.SC_MOVED_TEMPORARILY))
                assert false, "Bad Response Code"
            br = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()))
            String readLine
            while(((readLine = br.readLine()) != null)) {
                log.info("Response Data = " + readLine)
            }
            Header [] respHeaders = method.getResponseHeaders()
            respHeaders.each () {
                log.info(it.getName() + " = " + it.getValue())
                try {
                    returnData.setProperty(it.value.split("=")[0], it.value.split("=")[1])
                }
                catch (Exception exc) {
                    log.info("Could not split on equals sign = " + it.value)
                }
            }
        }
        def endTime = System.nanoTime()
        def duration = endTime - startTime;
        def seconds = (double)duration / 1000000000.0;
        log.info("Post took = " + seconds + " seconds (Post url = " + postData.getProperty("url") + ")")
        return returnData
    } catch (Exception exc) {
        log.info(exc.message, exc)
        return null
    } finally {
        method.releaseConnection()
        if(br != null) try {
            br.close()
        } catch (Exception fe) {
            log.info(fe.message, fe)
        }
    }
}
}

OP想要测试进行AJAX调用的页面。Selenium必须等待这些调用完成后,页面才能准备好。OP不想在测试中进行AJAX调用。正如您所指出的那样,如果要测试AJAX调用结果,则不需要涉及Selenium/Webdriver。(我不是downvoter,但我确信这就是为什么有downvoter的原因。) - Barett

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接