有些网站为了节省流量和资源,提高加载效率,采用的是动态加载(懒加载)的,也就是当拖动页面右侧滚动条后会自动加载网页下面的内容,不拖动就不会加载的或者通过鼠标滚轮操作。
wheel模拟鼠标滚动,就是通过调度一个wheel事件。(滚轮事件如果不处理可能会导致滚动,该方法不会等待滚动结束才返回。)语法如下:
def wheel(self, delta_x: float, delta_y: float) -> None: """Mouse.wheel Dispatches a `wheel` event. **NOTE** Wheel events may cause scrolling if they are not handled, and this method does not wait for the scrolling to finish before returning. Parameters ---------- delta_x : float Pixels to scroll horizontally. delta_y : float Pixels to scroll vertically. """
参数 |
类型 |
释义 |
---|---|---|
delta_x |
float |
要水平滚动的像素 |
delta_y |
float |
要垂直滚动的像素 |
mouse.wheel(delta_x, delta_y)
宏哥这里就用菜鸟教程的网站进行讲解和演示:一边滚动一边加载网页内容。
# coding=utf-8🔥 # 1.先设置编码,utf-8可支持中英文,如上,一般放在第一行 # 2.注释:包括记录创建时间,创建人,项目名称。 ''' Created on 2023-12-16 @author: 北京-宏哥 公众号:北京宏哥 Project: 《最新出炉》系列入门篇-Python+Playwright自动化测试-45-鼠标滚轮操作 ''' # 3.导入模块 from playwright.sync_api import Playwright, sync_playwright, expect def run(playwright: Playwright) -> None: browser = playwright.chromium.launch(headless=False) context = browser.new_context() page = context.new_page() page.goto("https://www.runoob.com/") page.wait_for_timeout(1000) for i in range(50): page.mouse.wheel(0, 100) page.wait_for_timeout(500) #page.pause() context.close() browser.close() with sync_playwright() as playwright: run(playwright)
1.运行代码,右键Run'Test',控制台输出,如下图所示:
2.运行代码后电脑端的浏览器的动作。如下图所示:
好了,今天时间也不早了,宏哥就讲解和分享到这里,感谢您耐心的阅读,希望对您有所帮助。