在无限滚动 Python 网页抓取时加载更多选项

时间:2021-07-12 12:31:35

标签: python python-3.x selenium web-scraping

试图滚动浏览网页 like this 并抓取他们的公司名称和描述。我无法破解滚动到达网页上的静止点后出现的“加载更多”选项。我怎样才能穿透“加载更多”并继续将内容存储在列表或 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()

Docs that helped me but never didn't fix the probelm overall

1 个答案:

答案 0 :(得分:0)

你为什么不试着爬过去

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=

运行 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

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