3

我一直在阅读有关如何在 Selenium webdriver 中处理 AJAX 的信息。有很多解决方案。有没有最好和正确的解决方案?

到目前为止,我读到的解决方案是:

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

谢谢!

4

4 回答 4

0

我已经使用了它,它本身等待工作正常。

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

谢谢试试。

于 2012-06-19T09:06:07.757 回答
0

处理 ajax 组件的可靠解决方案(在我的案例中使用)是使用 webdriver 的 waitUntil() API 调用等待元素在页面上可见。

否则,根本不建议使用类似 threadleep() 的解决方案来处理 Ajax。

于 2012-05-30T04:18:43.720 回答
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
于 2018-08-21T23:07:55.217 回答
-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)
        }
    }
}
}
于 2012-06-04T14:11:24.697 回答