如何正确滚动以加载更多结果?
如何确保单击“负载更多结果”按钮,直到没有更多结果可用? 任何指导都将不胜感激!
我对代码进行了一些更改,以使其适合您的情况:
# get rid of the cookie banner
coookie_button = WebDriverWait(driver, 5).until(
EC.element_to_be_clickable((By.ID, "onetrust-accept-btn-handler"))
)
coookie_button.click()
# Scroll to load more results using JavaScript on the client
prev_height = -1
max_scrolls = 100
scroll_count = 0
while scroll_count < max_scrolls:
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(1.5) # give some time for new results to load
new_height = driver.execute_script("return document.body.scrollHeight")
if new_height == prev_height:
# no more elements were loaded
break
prev_height = new_height
scroll_count += 1
# Now click the load more button while there are more results
while True:
try:
# choosing a good selector here is a bit tricky as there's
# nothing reliable but this works at the moment
load_more_button = WebDriverWait(driver, 5).until(
EC.element_to_be_clickable((By.CSS_SELECTOR, "[data-results-container=\"1\"] button.af7297d90d.c0e0affd09"))
)
load_more_button.click()
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
print("Clicked load more button...")
except (TimeoutException, NoSuchElementException):
print("No more results to load.")
break