You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

RSelenium/Python Selenium动态页面滚动爬取失效问题求解

解决方案:R与Python下实现Vivli搜索页面滚动加载

R(使用RSelenium)

你之前的滚动操作针对的是整个页面body,但实际搜索结果的滚动区域是特定容器元素,而非全局页面。按以下步骤操作:

  1. 定位搜索结果的滚动容器(通过浏览器F12开发者工具确认,通常是包裹所有搜索结果的可滚动div):
scroll_container <- remDr$findElement(using = 'xpath', '//*[@id="search-feature-container"]/div[2]/div[2]/div[3]/div[2]')
  1. 循环执行滚动脚本,直到没有新内容加载(通过对比滚动前后的容器高度判断):
previous_height <- 0
while(TRUE) {
  # 让容器滚动到底部
  remDr$executeScript("arguments[0].scrollTop = arguments[0].scrollHeight;", list(scroll_container))
  # 等待内容加载(根据页面速度调整时长)
  Sys.sleep(2)
  # 获取当前容器的滚动高度
  current_height <- remDr$executeScript("return arguments[0].scrollHeight;", list(scroll_container))
  # 高度不再变化则停止滚动
  if(current_height == previous_height) break
  previous_height <- current_height
}
  1. 加载完成后用rvest提取内容:
page_source <- remDr$getPageSource()[[1]]
html <- read_html(page_source)
# 后续编写提取逻辑...

Python(使用Selenium)

同样针对特定滚动容器操作,步骤如下:

  1. 初始化浏览器并完成搜索操作:
from selenium import webdriver
from selenium.webdriver.common.by import By
import time

driver = webdriver.Chrome()
driver.get("https://search.vivli.org/")
# 示例:输入搜索词并点击放大镜
search_box = driver.find_element(By.XPATH, "//input[@placeholder='Search...']")
search_box.send_keys("your_keyword")
driver.find_element(By.XPATH, "//button[@aria-label='Search']").click()
time.sleep(2)
  1. 定位滚动容器并循环滚动:
scroll_container = driver.find_element(By.XPATH, '//*[@id="search-feature-container"]/div[2]/div[2]/div[3]/div[2]')
previous_height = 0

while True:
    # 滚动容器到底部
    driver.execute_script("arguments[0].scrollTop = arguments[0].scrollHeight;", scroll_container)
    time.sleep(2)
    current_height = driver.execute_script("return arguments[0].scrollHeight;", scroll_container)
    if current_height == previous_height:
        break
    previous_height = current_height
  1. 用BeautifulSoup提取内容:
from bs4 import BeautifulSoup

page_source = driver.page_source
soup = BeautifulSoup(page_source, "html.parser")
# 后续编写提取逻辑...
driver.quit()

关键提示

  • 务必通过开发者工具确认滚动容器的正确XPATH,页面结构可能存在细微变动。
  • 等待时长需根据页面加载速度调整,避免因加载未完成导致判断错误。
  • 若JS滚动无效,可尝试模拟鼠标滚轮操作(Python用ActionChains,R用sendKeys模拟),但JS滚动容器的方式稳定性更强。

内容的提问来源于stack exchange,提问作者Abdullah Abdelaziz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 08:02:45