首页 > 解决方案 > 在无限滚动 Python 网页抓取时加载更多选项

问题描述

试图像这样滚动浏览网页并刮掉他们的公司名称和描述。一旦滚动在网页上达到静止点,我无法破解“加载更多”选项。我怎样才能穿透“加载更多”并继续将内容存储在列表或我可以稍后解析的 df 中?

from selenium import webdriver

driver = webdriver.Chrome()
driver.get("https://www.cloudstack.org/")
time.sleep(2)
scroll_pause_time = 1
screen_height = driver.execute_script("return window.screen.height;")
i = 1

while True:
    
    driver.execute_script("window.scrollTo(0, {screen_height}*{i});".format(screen_height=screen_height, i=i))  
    i += 1
    time.sleep(scroll_pause_time)
    
    scroll_height = driver.execute_script("return document.body.scrollHeight;")  
  
    if (screen_height) * i > scroll_height:
        break

html_source = driver.page_source
data = html_source.encode('utf-8')

我试过这个来点击加载更多,但在那之后我遇到了“ElementNotInteractableException”。

  load_more = driver.find_elements_by_class_name("next-selector")
    if load_more:
        load_more[0].click()

帮助我但从未整体解决问题的文档

标签: pythonpython-3.xseleniumweb-scraping

解决方案


你为什么不试着刮过

https://www.cloudtango.org/list/?page=1

有一个page参数可以根据需要进行更改。

还有其他论点,例如:

country=&service=&partner=&locality=&postal_town=&administrative_area_level_1=&administrative_area_level_2=&administrative_area_level_3=&autocomplete=&companyname=&head_office=&coordenades_lat=&coordenades_lng=&orderby=&order=

运行loop所需的页面,抓取页面并根据需要保存。不超过 200 页,但

这是演示代码:

driver = webdriver.Chrome()
i=0
while True:
    driver.get(f"https://www.cloudtango.org/list/?page={i}")
    i+=1
    if driver.title!="Where IT seekers find Cloud Service Providers - Cloudtango":
        break

我们正在使用无限循环,但我们每次都在检查标题。当我们到达终点时,无限循环将中断。


推荐阅读