简体   繁体   中英

Do/While infinitely loops issue c#

I am automating interaction with a website where the user will have to refresh the pages n times manually (sometimes 3 or 5 or even longer) so that the buttons appear on the web page. To overcome this issue, I created a do / while loop that should refresh the page until the button is visible so it can be clicked. The problem is it goes out of sync and infinitely loops. I tried the script below, but it still doesn't stop refreshing. Any idea how to make it stop refreshing as soon as the element is visible? by default, the element will not be visible, so the user will have to refresh the page first. The refresh works, but it is very quick, and it doesn't give enough time to check the state of visibility of the button, and maybe that's why it goes into an infinite loop

int retries = 0;
bool isElementVisible = false;
do {
  await Page.ReloadAsync(new PageReloadOptions() { Timeout = 5000 });
  isElementVisible = await Page.IsVisibleAsync("input[name='elementname']");
  retries ++;
while (!isElementVisible)

The problem with your code is that IsVisibleAsync will resolve to false immediately. You could wait for visible with some timeout using WaitForSelectorAsync . For instance, 5 seconds:

int retries = 0;
bool isElementVisible = false;
do {
  await Page.ReloadAsync(new PageReloadOptions() { Timeout = 5000 });
  try {
    // The default State is Visible
    await Page.WaitForSelectorAsync("input[name='elementname']", new(){ Timeout = 5000});
    isElementVisible = true;
  } catch(Exception ex) {
    retries ++;
  }
} while (!isElementVisible)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM