提问人:rusty 提问时间:11/10/2023 最后编辑:rusty 更新时间:11/11/2023 访问量:44
如何为动态表元素找到正确的等待命令?
How to find the correct wait command for a dynamic table element?
问:
该网站已 https://www.nseindia.com/get-quotes/derivatives?symbol=AARTIIND
这是我的代码:
driver.get("https://www.nseindia.com/get-quotes/derivatives?symbol=AARTIIND");
try {
wait.until(ExpectedConditions.elementToBeClickable(By.id("optionChain")));
} catch (Exception e) {
}
driver.findElement(By.id("optionChain")).click();
try {
wait.until(ExpectedConditions.numberOfElementsToBeMoreThan(By.xpath("/html/body/div[10]/div[1]/div/section/div/div/div/div/div[1]/div[2]/div/div/div/div[2]/div[2]/div[2]/div/table[1]/tbody/tr"), 10));
} catch (Exception e) {
}
Thread.sleep(10000);
List<WebElement> table = driver.findElements(By.xpath("/html/body/div[10]/div[1]/div/section/div/div/div/div/div[1]/div[2]/div/div/div/div[2]/div[2]/div[2]/div/table[1]/tbody/tr"));
int optionChainSize = table.size();
我想删除 Thread.sleep() 命令,但它总是以 optionChainSize = 0 结束。
我使用“wait.until(ExpectedConditions...”等待“选项链”元素加载,然后单击它。此后出现一个表,但尽我所能,我无法让程序等待它加载,除了一个粗略的 Thread.sleep 命令。
我试过写着“tot”的底行,右上角写着“Underlying:”,但它们似乎都只是在表格之前加载。我尝试了“numberOfElementsToBeMoreThan”并放置了“tr”xpath的定位器,如下所示:
try {
wait.until(ExpectedConditions.numberOfElementsToBeMoreThan(By.xpath("/html/body/div[10]/div[1]/div/section/div/div/div/div/div[1]/div[2]/div/div/div/div[2]/div[2]/div[2]/div/table[1]/tbody/tr"), 10));
} catch (Exception e) {
有什么方法可以做到这一点吗?我不明白“陈旧”属性,这有用吗?
答:
0赞
Bhairu
11/10/2023
#1
**Solution 1:**
Please try the below mechanism, actually, it will be polling every second and it stops the polling once you it get the desired element, it might work for you.
FluentWait<WebDriver> wait = new FluentWait<> (driver)
.withTimeout (10, TimeUnit.SECONDS)
.pollingEvery (1, TimeUnit.SECONDS)
.ignoring (NoSuchElementException.class);
// Define the locator of the element to be clicked
By locator = By.id("");
// Wait until the element is clickable
WebElement element = wait.until (ExpectedConditions.elementToBeClickable (locator));
// Click on the element
element.click();
**Solutions 2:**
here you can use the if-else condition to wait for until desired element.
//add loop
for(i=0;i<=10)
{
boolean WaitforThisElement=driver.findelement(By.xpath("pass the path of the waiting elememnt").isDisplayed();
if(WaitforThisElement==true)
{
//write the code for the further activities.
//if the desired element is found it cannot move to the else block and will end the loop and come out from the loop and move to the next code.
}
else
{
//wait for the 10 seconds.
Thread.wait(10000);
//Increase the loop count
i++
}
}
评论
0赞
rusty
11/11/2023
我正在努力寻找元素本身。所需的元素是我找不到的。表之后加载什么元素?
0赞
Bhairu
11/15/2023
@rusty 首先手动签入,然后查看加载元素需要多少时间,然后根据您的编码进行抓取。
评论