如何使用Selenium在非整页滚动面板中滚动?爬取Pikalytics遇阻
解决Pikalytics左侧面板滚动加载数据的问题
问题根源
send_keys(Keys.PAGE_DOWN)报错是因为目标元素并非可获取焦点的交互元素,且左侧面板的滚动依赖内部滚动容器,而非页面整体滚动逻辑。
可行解决方案
方案1:用JavaScript直接操控滚动容器
找到左侧面板的滚动容器(通常是带有overflow: auto样式的元素),通过JS修改其scrollTop属性触发滚动加载。
示例代码:
from selenium import webdriver from selenium.webdriver.common.by import By import time driver = webdriver.Chrome() driver.get('https://www.pikalytics.com') time.sleep(2) # 等待页面初始加载完成 # 定位左侧滚动容器 scroll_container = driver.find_element(By.ID, 'mini_list_wrapper') # 循环滚动直至加载全部数据 last_height = driver.execute_script("return arguments[0].scrollHeight", scroll_container) while True: # 滚动到容器底部 driver.execute_script("arguments[0].scrollTop = arguments[0].scrollHeight", scroll_container) time.sleep(1) # 等待数据加载 new_height = driver.execute_script("return arguments[0].scrollHeight", scroll_container) if new_height == last_height: break # 高度不再变化说明无新数据 last_height = new_height # 此时可获取完整页面源码进行解析 soup = BeautifulSoup(driver.page_source, 'html.parser') # 后续数据解析操作...
方案2:模拟鼠标滚轮滚动
若JS修改scrollTop无效,可通过ActionChains模拟鼠标在面板内滚动滚轮。
示例代码:
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.action_chains import ActionChains import time driver = webdriver.Chrome() driver.get('https://www.pikalytics.com') time.sleep(2) scroll_container = driver.find_element(By.ID, 'mini_list_wrapper') action = ActionChains(driver) # 先将鼠标移至容器上,确保滚动目标正确 action.move_to_element(scroll_container).perform() last_height = driver.execute_script("return arguments[0].scrollHeight", scroll_container) while True: # 模拟向下滚动(每次滚动300像素,可根据加载速度调整) action.scroll_by_amount(0, 300).perform() time.sleep(1) new_height = driver.execute_script("return arguments[0].scrollHeight", scroll_container) if new_height == last_height: break last_height = new_height # 后续数据解析操作...
关键注意点
- 优先使用显式等待替代
time.sleep(),避免因页面加载慢导致元素定位失败:from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC scroll_container = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.ID, 'mini_list_wrapper')) ) - 滚动间隔时间需根据页面加载速度调整,防止因加载不充分漏爬数据。
内容的提问来源于stack exchange,提问作者Qwiny
相关产品推荐
相关产品推荐

