简体   繁体   English

Do/While 无限循环发出 c#

[英]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.我正在自动与用户必须手动刷新页面 n 次(有时 3 或 5 甚至更长)的网站交互,以便按钮出现在 web 页面上。 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.为了克服这个问题,我创建了一个 do / while 循环,它应该刷新页面,直到按钮可见,以便可以单击它。 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刷新有效,但速度非常快,并且没有足够的时间检查按钮的可见性 state,也许这就是它进入无限循环的原因

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.您的代码的问题是IsVisibleAsync将立即解析为 false。 You could wait for visible with some timeout using WaitForSelectorAsync .您可以使用WaitForSelectorAsync等待一段时间的可见。 For instance, 5 seconds:例如,5 秒:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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