Python使用Selenium实现页面滚动

  • 2021年7月21日
  • 技术

在爬取epic的游戏信息时,发现epic的游戏列表并不是点击翻页方式的,而是使用懒加载,不然不能完全获取到页面的内容,于是需要Selenium来实现页面滚动。

# -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_argument("--headless --window-size=1920,1080")  # 后台运行模式,不会弹出窗口和设置窗口大小
browser = webdriver.Chrome(r"F:\python\chromedriver_win32\chromedriver.exe" , options=chrome_options)  # 使用chrome无头浏览器

browser.get("https://www.epicgames.com/store/zh-CN/browse?sortBy=releaseDate&sortDir=DESC&count=40&start=0")  # 打开epic浏览页面页面
browser.implicitly_wait(10)  # 等待一定时间,让js脚本加载完毕

for i in range(1, 2):  # 滚动
    height = 500 * i
    browser.execute_script('window.scrollTo(0, %s)' % (height))
    time.sleep(3)

html_page = browser.page_source.encode('utf-8').decode()  # 取得网页的源代码
browser.quit()
return html_page;
execute_script方法介绍:

是selenium提供了一个操作js的方法,可以直接执行js的脚本。

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注