gpt4 book ai didi

java - 在selenium中使用javascript监听AJAX请求

转载 作者:行者123 更新时间:2023-11-28 09:32:17 24 4
gpt4 key购买 nike

所以我知道如何使用 Selenium,并且我想创建一个聊天机器人。但是,我无权访问源代码,聊天是自定义编写的页面。这个页面正在发出 GET 请求,然后网站返回我想要的内容。我想使用 Selenium 来运行 javascript (我知道该怎么做),它要么等待下一个 GET 返回,要么返回最新 GET 返回的内容。那时我可以解析出我不需要的东西。

我尝试过寻找一个 JavaScript 函数来执行此操作,但我所能做的就是找到监听请求的函数,而不是监听响应的函数。谢谢!注意:接下来我将在此页面上保持活跃状态​​,因此如果您需要代码等,请务必询问!

最佳答案

使用 FluentWait() 机制等待所有 ajax 怎么样:

public WebElement fluentWait(final By locator){
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(30, TimeUnit.SECONDS)
.pollingEvery(5, TimeUnit.SECONDS)
.ignoring(org.openqa.selenium.NoSuchElementException.class);
WebElement foo = wait.until(
new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver driver) {
return driver.findElement(locator);
}
}
);
return foo; } ;

fluentWait(By.xpath(...blablabla...));
//fluentWait(By.cssSelector(...blablabla...));

然后可以进行js注入(inject):

 public void jsCodeExecution(String jsCode){
JavascriptExecutor js = (JavascriptExecutor)driver;
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(jsCode);
js.executeScript(stringBuilder.toString());
}

或者立即使用 jsInjection 。 How does JavaScript handle AJAX responses

关于java - 在selenium中使用javascript监听AJAX请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13592933/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com