python中scroll的用法_如何使用Python获取整个scroll元素的屏幕截图

from PIL import Image

from io import BytesIO

from selenium import webdriver

from selenium.webdriver.chrome.options import Options

def open_url(url):

options = Options()

options.headless = True

driver = webdriver.Chrome(chrome_options=options)

driver.maximize_window()

driver.get(url)

save_screenshot(driver, 'screen.png')

def save_screenshot(driver, file_name):

height, width = scroll_down(driver)

driver.set_window_size(width, height)

img_binary = driver.get_screenshot_as_png()

img = Image.open(BytesIO(img_binary))

img.save(file_name)

# print(file_name)

print(" screenshot saved ")

def scroll_down(driver):

total_width = driver.execute_script("return document.body.offsetWidth")

total_height = driver.execute_script("return document.body.parentNode.scrollHeight")

viewport_width = driver.execute_script("return document.body.clientWidth")

viewport_height = driver.execute_script("return window.innerHeight")

rectangles = []

i = 0

while i < total_height:

ii = 0

top_height = i + viewport_height

if top_height > total_height:

top_height = total_height

while ii < total_width:

top_width = ii + viewport_width

if top_width > total_width:

top_width = total_width

rectangles.append((ii, i, top_width, top_height))

ii = ii + viewport_width

i = i + viewport_height

previous = None

part = 0

for rectangle in rectangles:

if not previous is None:

driver.execute_script("window.scrollTo({0}, {1})".format(rectangle[0], rectangle[1]))

time.sleep(0.5)

# time.sleep(0.2)

if rectangle[1] + viewport_height > total_height:

offset = (rectangle[0], total_height - viewport_height)

else:

offset = (rectangle[0], rectangle[1])

previous = rectangle

return (total_height, total_width)

open_url("https://www.medium.com")

向下滚动函数滚动到页面底部并返回网页的总高度和宽度。在

保存截图功能设置窗口大小并使用枕头保存屏幕截图。在

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值