from selenium import webdriver from selenium.webdriver.common.keys import Keys import time # 初始化WebDriver,这里以Chrome为例 driver = webdriver.Chrome(executable_path='path_to_chromedriver.exe') # 打开要爬取的页面 url = 'https://example.com' # 替换为您要爬取的网页URL driver.get(url) # 模拟滚动到页面底部加载更多数据 SCROLL_PAUSE_TIME = 2 # 获取当前页面的高度 last_height = driver.execute_script("return document.body.scrollHeight") while True: # 模拟滚动到页面底部 driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") # 等待页面加载 time.sleep(SCROLL_PAUSE_TIME) # 获取新的页面高度 new_height = driver.execute_script("return document.body.scrollHeight") # 如果新的页面高度和上次高度相同,说明页面已经滚动到底部,退出循环 if new_height == last_height: break last_height = new_height # 页面已经滚动到底部,可以开始提取数据 # 使用Selenium的方法提取您需要的数据,比如通过Xpath或CSS Selector等 # 示例:假设目标数据在class为"item"的元素中 elements = driver.find_elements_by_class_name("item") # 遍历提取数据 for element in elements: # 处理每个元素的数据 data = element.text print(data) # 关闭WebDriver driver.quit()
在上述代码中,我们通过模拟滚动操作不断加载更多数据,直到页面滚动到底部。然后使用Selenium提取我们需要的数据。请根据您要爬取的网页的实际情况,调整代码中的元素查找方式(例如使用Xpath或CSS Selector等)和数据提取方法。请注意,使用Selenium进行页面滚动和数据提取时,需要注意网站的反爬虫策略,以避免触发反爬虫机制。在实际应用中,请尊重网站的Robots.txt规则,并设置合适的访问频率和延时,避免对目标网站造成过大的访问压力。
网友回复