[英]Recursive Python function not returning appropriate value
我寫了一個 function 來滾動一個使用無限滾動的頁面,使用 selenium 我執行一個腳本滾動到底部,休眠幾秒鍾(讓頁面有時間加載更多內容),並檢查當前滾動是否position 等於最后一個卷軸 position(表示這是頁面的真正結尾)。 在下面的段中, end_of_scroll_region
永遠不會變為真,而 while 循環會無限期地運行。
last_position = None
end_of_scroll_region = False
while not end_of_scroll_region:
last_position, end_of_scroll_region = scroll_down_page(driver, last_position)
scroll_down_page
function 實際上執行滾動腳本並包含一個遞歸邏輯來重試滾動過程,以解決頁面需要更多時間加載的情況,方法是使用嘗試計數器和增加的睡眠時間再次滾動。 但經過無數次調試后,我發現end_of_scroll_region
變為 True 但立即變回 False(假設回調中發生了某些事情)。
def scroll_down_page(driver, last_position, num_seconds_to_load=0.5, scroll_attempt=0, max_attempts=5):
end_of_scroll_region = False
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
sleep(num_seconds_to_load)
curr_position = driver.execute_script("return window.pageYOffset;")
if curr_position == last_position:
if scroll_attempt == max_attempts:
end_of_scroll_region = True
else:
scroll_down_page(driver, last_position, num_seconds_to_load+5, scroll_attempt + 1, max_attempts)
last_position = curr_position
return last_position, end_of_scroll_region
正如評論中提到的,我沒有從對scroll_down_page
的遞歸調用中捕獲返回值
def scroll_down_page(driver, last_position, num_seconds_to_load=0.5, scroll_attempt=0, max_attempts=5):
end_of_scroll_region = False
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
sleep(num_seconds_to_load)
curr_position = driver.execute_script("return window.pageYOffset;")
if curr_position == last_position:
if scroll_attempt == max_attempts:
end_of_scroll_region = True
else:
#Solution
last_position, end_of_scroll_region = scroll_down_page(driver, last_position, num_seconds_to_load+5, scroll_attempt + 1, max_attempts)
last_position = curr_position
return last_position, end_of_scroll_region
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.