Selenium 实现事件监听

介绍

前面的文章详细介绍了Selenium4.0的使用方法,我们打开Selenium的包发现里面有两个比较实用的工具。abstract_event_listener.py(抽象事件监听器)、event_firing_webdriver(webdriver事件触发器),看一下代码发现,这两个工具可以实现Selenium事件监听,监听点击、输入、跳转等操作。

抽象事件监听器

通过查看代码发现,抽象事件监听器是一些操作的抽象监听方法,我们可以写一些监听方法来实现这些监听器。但是,通过和Java包的对比发现python包的监听器功能比Java要少好多。有兴趣的同学可以看一下Java包的代码。

class AbstractEventListener:
    """Event listener must subclass and implement this fully or partially."""

    def before_navigate_to(self, url: str, driver) -> None:
        pass

    def after_navigate_to(self, url: str, driver) -> None:
        pass

    def before_navigate_back(self, driver) -> None:
        pass

    def after_navigate_back(self, driver) -> None:
        pass

    def before_navigate_forward(self, driver) -> None:
        pass

    def after_navigate_forward(self, driver) -> None:
        pass

    def before_find(self, by, value, driver) -> None:
        pass

    def after_find(self, by, value, driver) -> None:
        pass

    def before_click(self, element, driver) -> None:
        pass

    def after_click(self, element, driver) -> None:
        pass

    def before_change_value_of(self, element, driver) -> None:
        pass

    def after_change_value_of(self, element, driver) -> None:
        pass

    def before_execute_script(self, script, driver) -> None:
        pass

    def after_execute_script(self, script, driver) -> None:
        pass

    def before_close(self, driver) -> None:
        pass

    def after_close(self, driver) -> None:
        pass

    def before_quit(self, driver) -> None:
        pass

    def after_quit(self, driver) -> None:
        pass

    def on_exception(self, exception, driver) -> None:
        pass

webdriver事件触发器

从触发器的代码可以看出来,触发器需要传递两个参数,一个是WebDriver类型的参数,一个抽象事件监听器类型。

class EventFiringWebDriver:
    """A wrapper around an arbitrary WebDriver instance which supports firing
    events."""

    def __init__(self, driver: WebDriver, event_listener: AbstractEventListener) -> None:
        """Creates a new instance of the EventFiringWebDriver.

        :Args:
         - driver : A WebDriver instance
         - event_listener : Instance of a class that subclasses AbstractEventListener and implements it fully or partially

        Example:

        ::

            from selenium.webdriver import Firefox
            from selenium.webdriver.support.events import EventFiringWebDriver, AbstractEventListener

            class MyListener(AbstractEventListener):
                def before_navigate_to(self, url, driver):
                    print("Before navigate to %s" % url)
                def after_navigate_to(self, url, driver):
                    print("After navigate to %s" % url)

            driver = Firefox()
            ef_driver = EventFiringWebDriver(driver, MyListener())
            ef_driver.get("http://www.google.co.in/")
        """
        if not isinstance(driver, WebDriver):
            raise WebDriverException("A WebDriver instance must be supplied")
        if not isinstance(event_listener, AbstractEventListener):
            raise WebDriverException("Event listener must be a subclass of AbstractEventListener")
        self._driver = driver
        self._driver._wrap_value = self._wrap_value
        self._listener = event_listener

实现抽象事件监听器

监听点击事件

from selenium.webdriver.support.abstract_event_listener import AbstractEventListener


class PageListener(AbstractEventListener):

    def before_click(self, element, driver) -> None:
        print("监听点击事件执行前")
        
    def after_click(self, element, driver) -> None:
        print("监听点击事件执行后")

编写Selenium脚本,执行点击操作。

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.event_firing_webdriver import EventFiringWebDriver
from page_listener import PageListener

driver = webdriver.Chrome()
listener = PageListener()
ef_driver = EventFiringWebDriver(driver, listener)
ef_driver.get('http://www.baidu.com')
ef_driver.find_element(by=By.XPATH, value='//*[@id="su"]').click()

"""
监听点击事件执行前
监听点击事件执行后

Process finished with exit code 0
"""

监听输入事件

from selenium.webdriver.support.abstract_event_listener import AbstractEventListener


class PageListener(AbstractEventListener):

    def before_quit(self, driver) -> None:
        print("监听退出事件前")

    def after_quit(self, driver) -> None:
        print("监听退出事件后")

编写Selenium执行退出操作的脚本。

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.event_firing_webdriver import EventFiringWebDriver
from page_listener import PageListener

driver = webdriver.Chrome()
listener = PageListener()
ef_driver = EventFiringWebDriver(driver, listener)
ef_driver.get('http://www.baidu.com')
ef_driver.find_element(by=By.XPATH, value='//*[@id="kw"]').send_keys('百度')
ef_driver.quit()

"""
监听退出事件前
监听退出事件后

Process finished with exit code 0
"""

总结#

从上面的实例可以看出来,我们已经实现了部分事件监听器,那么都有哪些监听方法呢,我们用的是Selenium目前最新的版本4.24。python版本的Selenium,只支持19个监听方法。对比Java支持的监听方法比较少,Java的Selenium4.24版本的监听方法有143个。下面是Python版Selenium支持的监听方法。

class AbstractEventListener:
    """Event listener must subclass and implement this fully or partially."""

    def before_navigate_to(self, url: str, driver) -> None:
        pass

    def after_navigate_to(self, url: str, driver) -> None:
        pass

    def before_navigate_back(self, driver) -> None:
        pass

    def after_navigate_back(self, driver) -> None:
        pass

    def before_navigate_forward(self, driver) -> None:
        pass

    def after_navigate_forward(self, driver) -> None:
        pass

    def before_find(self, by, value, driver) -> None:
        pass

    def after_find(self, by, value, driver) -> None:
        pass

    def before_click(self, element, driver) -> None:
        pass

    def after_click(self, element, driver) -> None:
        pass

    def before_change_value_of(self, element, driver) -> None:
        pass

    def after_change_value_of(self, element, driver) -> None:
        pass

    def before_execute_script(self, script, driver) -> None:
        pass

    def after_execute_script(self, script, driver) -> None:
        pass

    def before_close(self, driver) -> None:
        pass

    def after_close(self, driver) -> None:
        pass

    def before_quit(self, driver) -> None:
        pass

    def after_quit(self, driver) -> None:
        pass

    def on_exception(self, exception, driver) -> None:
        pass
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值