Click on pseudo element using Selenium

前端 未结 4 1079
清歌不尽
清歌不尽 2020-12-31 08:53

I am trying to use Selenium to click on a ::after pseudo element. I realize that this cannot be done through the WebDriver directly, but cannot seem to figure out a way to d

4条回答
  •  傲寒
    傲寒 (楼主)
    2020-12-31 09:27

    Im going to provide an alternative that may work for some scenarios, at least it did the trick for me, and is relatively easy to implement in any language using selenium via a JS script.

    In my scenario there was an ::after pseudoelement containing the functionality of a button. This button was contained in a position relative to another element under it.

    So I did the following:

    1. Get the element that I can, in this question scenario would be that span.
    2. Get the coordinates of the element.
    3. Calculate the coordinates realtive to that element of the pseudoelement you want to click.
    4. Click on those coordinates.

    This is my code using perl, but I'm sure you can do the same in any language:

    my $script="
    function click_function(x, y)
    {
        console.log('Clicking: ' + x + ' ' + y);
    
        var ev = new MouseEvent('click', {
            'view': window,
            'bubbles': true,
            'cancelable': true,
            'screenX': x,
            'screenY': y
        });
    
        var el = document.elementFromPoint(x, y);
    
        el.dispatchEvent(ev);
    }
    
    var element = document.getElementById('here_put_your_id'); //replace elementId with your element's Id.
    var rect = element.getBoundingClientRect();
    var elementLeft,elementTop; //x and y
    var scrollTop = document.documentElement.scrollTop?
                   document.documentElement.scrollTop:document.body.scrollTop;
    var scrollLeft = document.documentElement.scrollLeft?            
    
        document.documentElement.scrollLeft:document.body.scrollLeft;
    elementTop = rect.top+scrollTop;
    elementLeft = rect.left+scrollLeft;
    console.log('Coordiantes: ' + elementLeft + ' ' + elementTop)
    
    click_function(elementLeft*1.88, elementTop*1.045) // here put yor relative coordiantes
        ";
        $driver->execute_script($script);
    

提交回复
热议问题