如何使用python booking.com中的硒滚动并单击“加载更多结果”。 我是新来的网络刮擦,selenium,我正在尝试从booking.com刮擦属性列表。我的代码(如下)成功刮擦了25个结果,但我怀疑问题是更多...

问题描述 投票:0回答:1
我要问什么:

如何正确滚动以加载更多结果?

如何确保单击“负载更多结果”按钮,直到没有更多结果可用? 任何指导都将不胜感激!


    

我对代码进行了一些更改,以使其适合您的情况:

    当用户滚动时,第一个结果会自动加载,因此首先我们需要滚动到页面底部几次
  1. 然后出现“加载更多按钮”,我们需要正确找到它,然后单击IT
  2. 我还关闭了曲奇横幅,因为它正在干扰点击按钮
python selenium-webdriver web-scraping
1个回答
0
投票
这里是相关部分:

# 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
  • 使用上面的代码,我可以为您的搜索查询提取981个项目。 代码可以改进,但可以正常工作并显示了这个想法,我认为您可以根据需要进一步改进它。 希望这有帮助!
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.