Identifying button clicks using selenium-wire in Python

Is there a way to use selenium-wire in python to capture a full screenshot of a web page and save it as a png file after clicking the submit button?

Despite seeing a popup message saying "taking screenshot!!", the actual screenshot file is not being saved. Here's what I've tried:

    html2canvas = """
    var s = window.document.createElement('script');
    s.src = 'https://html2canvas.hertzen.com/dist/html2canvas.min.js';
    window.document.head.appendChild(s);
    """

    driver.execute_script(html2canvas)

    script = """
        btn = document.getElementById("input_2")
        btn.addEventListener("click", () => {
        alert('taking screenshot!!');
         // creating canvas of element using html2canvas
          html2canvas(srcElement).then(canvas => {
            // adding canvas/screenshot to the body
            if(btn.id === "take-src-only") {
              return document.body.appendChild(canvas);
            }
            // downloading canvas/screenshot
            const a = document.createElement("a");
            a.href = canvas.toDataURL();
            a.download = "fullscreenshot.png";
            a.click();
          });
        });
    """

    driver.execute_script(script)

Answer №1

Be sure to refer to the following document for more information on capturing element screenshots: https://www.selenium.dev/documentation/webdriver/interactions/windows/#takeelementscreenshot

import selenium
from selenium import webdriver
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()

driver.get("http://www.example.com")

element = driver.find_element(By.CSS_SELECTOR, 'h1')
input2 = driver.find_element(By.ID, 'input_2')
    # Encodes the screenshot of the element as a base64 string
input2.click()
element.screenshot('./image.png')

#or 
driver.save_screenshot('./image.png')

driver.quit()

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a specific index range in javascript or nodejs for accessing array items?

I recently came across this Ruby code snippet: module Plutus TAX_RATES = { (0..18_200) => { base_tax_amount: 0, tax_rate: 0 }, (18_201..37_000) => { base_tax_amount: 0, tax_rate: 0.19 }, (37_001..80_0 ...

The call signatures for `node-fetch -- typeof import("[...]/node-fetch/index")'` are not properly defined

Originated from this source: https://github.com/node-fetch/node-fetch#json ... my personal code: const fetch = require('node-fetch'); async function doFetch() { const response = await fetch('https://api.github.com/users/github'); ...

Retrieve the name of the file from a given URL by using JavaScript/jQuery, even when only the directory path is

I need to extract the current filename from the URL using: $currentFile = window.location.pathname.split("/").pop(); This method functions properly when the full path looks like: http://www.yoursite.com/folder/index.php It will return index.php, index. ...

Shifting annotations on a Bar Graph featuring Negative Values on Google's Chart Maker

Incorporating google charts into my MVC project. Looking to create a bar chart that accommodates negative values. Desire annotations on the same side as the end of the bar for negative values (similar to positive values shown in the green box below). ht ...

``So, you're looking to retrieve a collection of objects that have a OneToMany

Is there a way to retrieve a list of objects with a OneToMany relation using TypeORM's queryBuilder? This is the desired output: { "id": 1, "firstName": "Bob", "lastName": "Sparrow", "orders": [ { "id": 1, "name": "Very Big Or ...

What could be causing the erratic jumping behavior of the "newsletter sign-up" form within my modal dialog window?

On the homepage, there is a modal window that appears upon every pageload (it will be changed later), however, there seems to be an issue with the 'email sign up' form inside the window. The form seems to momentarily display at the top of the si ...

Steps to create a personalized material-ui element

I am looking to create a custom time duration component by modifying the TextField component. https://i.stack.imgur.com/fLsFs.png https://i.stack.imgur.com/SdpdH.png If anyone has any advice or assistance, it would be greatly appreciated. Thank you! ...

Arrangement of watch attachment and $timeout binding

I recently encountered a component code that sets the HTML content using $scope.htmlContent = $sce.trustAsHtml(content). Subsequently, it calls a function within a $timeout to search for an element inside that content using $element.find('.stuff' ...

Error: The Tabs component is expecting a different `value`. The Tab with the current `value` ("0") is not present in the document structure

I am encountering an issue while using MUI tabs. The error message I receive is as follows: MUI: The value assigned to the Tabs component is not valid. The Tab with this value ("0") does not exist in the document layout. Please ensure that the tab item is ...

Deciphering JSON data into PHP arrays and variables: A step-by-step guide

As a PHP beginner, I'm struggling to grasp certain concepts related to extracting data from POST requests in PHP. Let me describe my code and the issue I'm facing: I have a serialized array that I convert to JSON before sending it via ajax to PH ...

Choosing between classes and styles for styling components in ReactJS

Can you explain why the call to the classes object works in the code below, rather than to the styles object defined as a const at the beginning? For instance, take a look at this demo: className={classes.button} The above line functions correctly. Howe ...

Issue encountered when implementing promise and await within a Vue method

I've implemented a function in the mounted() hook to fetch files from my Dropbox account using a promise. Once the promise is resolved successfully, I iterate through all the files and execute another promise function to retrieve additional informatio ...

How do I initiate PUT and DELETE requests from my HTML code?

I am currently in the process of developing a web application that will manage items within a list. Previously, I used buttons with event listeners and JavaScript functions to handle editing and deleting items. However, I am now transitioning towards build ...

Creating custom shaders in three.js that can receive shadows involves a few key steps. Let

For more information, you can visit the original post here. The task at hand seems to be quite complex due to the lack of documentation and examples on this specific topic on the three.js website. Currently, I am able to render the correct image and, with ...

Get the png image file and display a preview of it

Within my template, I have an img tag that is linked to a state known as "imageBuffer" <img v-bind:src="imageBuffer" alt="" /> In the logic of the page, there are two file inputs and I've utilized a single function to manag ...

Nothing is in the Laravel array when using `$request->all()`

In the process of developing a shopping cart using Laravel. Here are the details : Routes : Route::post('/cart/add', 'CartController@store')->name('cart.store'); Route::patch('/cart/{product}', 'CartContro ...

What is the process for incorporating a Bootstrap link into a specific ReactJS file?

In my current project using React JS, I found the need to incorporate Bootstrap in certain pages. To do this, I initially placed the following code snippet in the Public folder within index.html: <link rel="stylesheet" href="https://netdna.bootstrapc ...

What is the best way to transfer data in a JavaScript onclick event and then retrieve it in the click handler function?

I've been struggling with this issue for some time now. When researching the onclick JavaScript call, I noticed that sometimes it is written as onClick with a capital C, while other times it's simply onclick. The code I'm working on is part ...

Access the array values by their respective keys in an object that is returned from a custom JavaScript file utilizing the Node.js file system

I recently came across a config file with a unique format, as shown below: define([], function () { return { productItems: { item1: ['Apple', 'Ball', 'Car'], item2: [&apo ...

Error: A DOMException was caught in the promise while trying to push the router

Currently, I am facing an issue while working with React. An Uncaught DOMException occurs when trying to push the router. This exception specifically happens when I attempt to push a new URL into the router using an event triggered from a button in a mod ...