定义 超时 (将允许经过的指定时间段)以摆脱硬编码的延迟。超时需要进行硬编码。
此代码与原始代码之间的区别是:
- 循环本身一遍又一遍地运行(每次迭代不等待6秒),并检查是否有新内容,直到找到新内容或达到超时为止。
- 如果延迟加载花费的时间比预期的要长,例如在将数字21加载到50时,循环将“等待”并尝试获取超时中定义的最大时间的新内容。
- 缺点:在加载所有内容的最后一步,循环将花费与设置超时相同的秒数。
码:
Sub Getlinks() Dim driver As New ChromeDriver, prevlen&, curlen& Dim posts As Object, post As Object Dim timeout As Integer, startTime As Double timeout = 10 ' set the timeout to 10 seconds With driver .get "http://fortune.com/fortune500/list/" prevlen = .FindElementsByClass("company-title").Count startTime = Timer ' set the initial starting time Do .Executescript ("window.scrollTo(0, document.body.scrollHeight);") Set posts = .FindElementsByClass("company-title") curlen = posts.Count If curlen > prevlen Then startTime = Timer ' reset start time if new elements found prevlen = curlen ' set new prevlen End If Loop While Round(Timer - startTime, 2) <= timeout ' check if timeout is reached For Each post In posts R = R + 1: Cells(R, 1) = post.Text Next post End WithEnd Sub


