Utilizing JavaScript in Selenium WebDriver, what's the procedure for extracting element information from a script tag?

I'm facing an issue with this particular page

There is a canvas element on this page that displays changing numbers whenever the page is refreshed or reloaded.

Looking at the source code, I can only find the following:

<div class="row">
      <div class="large-10 columns">
        <canvas id="canvas" width="599" height="200" style="border:1px dotted;"></canvas>
      </div>
    </div>

Essentially, there's not much I can do with this information in the outer html. However, upon checking the network section and inspecting the response code, I discovered the following javascript code:

    <script>var canvas_el = document.getElementById('canvas');
var canvas = canvas_el.getContext('2d');
canvas.font = '60px Arial';
canvas.strokeText('Answer: 19403',90,112);
</script>

My current dilemma is how to write javascript (I'm not very experienced in it) in selenium webdriver to retrieve the details, specifically the strokeText under the script tag, which are not directly available in the source code. I'm seeking a solution that involves using JavascriptExecutor.

Answer №1

Your approach using JavascriptExecutor was on the right track. I discovered a helpful method outlined here.

final By SCRIPT = By.tagName("script");

List<WebElement> scripts = new WebDriverWait(driver, 5)
        .until(ExpectedConditions.presenceOfAllElementsLocatedBy(SCRIPT));

JavascriptExecutor js = (JavascriptExecutor) driver;
String query = "return document.getElementsByTagName(\"script\")[arguments[0]].innerHTML;";     
Pattern p = Pattern.compile("canvas.strokeText\\('Answer: \\d+'");
Pattern p2 = Pattern.compile("\\d+");

String number = IntStream.range(0, scripts.size())
        .mapToObj(i -> (String)js.executeScript(query, i))
        .map(string -> p.matcher(string))
        .filter(m -> m.find())
        .map(m -> p2.matcher(m.group()))
        .filter(m -> m.find())
        .map(m -> m.group())
        .findFirst()
        .orElse(null);
System.out.println(number);  // displays the number on the webpage

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

Checkbox: Activate button upon checkbox being selected

On my webpage, I have a modal window with 2 checkboxes. I want to enable the send button and change the background color (gray if disabled, red if enabled) when both checkboxes are selected. How can I achieve this effectively? HTML: <form action="" me ...

In my Django html file, I am facing an issue with the IF statement that seems to be dysfunctional

I have a like button and I want it to display an already liked button if the user has already liked the post. Here is my HTML: {% for post in posts %} <div class="border-solid border-2 mr-10 ml-10 mt-3 px-2 pb-4"> & ...

Checking if the current time falls within a specific range while also taking minutes into account

I am currently working on a website for restaurants offering home delivery services. I need to enable or disable the 'Order Now' button based on the designated home delivery timings of each restaurant. For this purpose, I have access to the star ...

What is the proper method for sending a value using the XMLHTTPRequest Object?

In my table, I have a set of dynamically generated links. Each row in the table has a unique "id" property in its tag. The main objective is to use XMLHTTPRequest to inform the 'deletepost.php' page which specific record needs to be removed from ...

WebGL Tips: Resizing an object using vector multiplication, achievement showcased (see image)

I'm currently exploring methods to scale an object without taking into consideration its local rotation. While I have achieved some success using morph animation, I am searching for a more dependable solution. ...

The array filtering functionality is not functioning as intended

Struggling with correctly filtering data in JavaScript. Here's an example where var1 = 20, var2 = 10, var3 = 30, var4 = 40. This is the code snippet: var variables = ['var1', 'var2', 'var3', 'var4'], values = [ ...

Error message: `Socket.io-client - Invalid TypeError: Expected a function for socket_io_client_1.default`

I have successfully installed socket.io-client in my Angular 5.2 application, but after trying to connect (which has worked flawlessly in the past), I am encountering a strange error. TypeError: socket_io_client_1.default is not a function at new Auth ...

Both an Angular and Java application seamlessly operating within a single domain

Recently Updated: Project 1: PHP, HTML, CSS, Java, mySQL Project 2: Angular, Spring Boot, PostgreSQL I am currently working on breaking off a part of Project 1 into a separate project (Project 2) that will operate independently with its own database. ...

Is it possible to utilize a route path in a JavaScript AJAX request?

So I have a situation with an ajax call that is currently functioning in a .js file, utilizing: ... update: function(){ $.ajax({ url: '/groups/order_links', ... However, my preference would be to use the route path instead. To achieve ...

Using Vue JS to display information conditionally within a single component

I currently have a component that dynamically displays the data from an array of objects. However, I want the component to display only one object based on a specific condition. Is it possible to show either one object or another depending on the value o ...

Steps for referencing an autogenerated id in a Firestore collection

I need assistance updating a 'progress' field in a document with an autogenerated ID (using Firestore) every time the progress button is clicked. https://i.stack.imgur.com/hZieN.png Despite my attempts, nothing seems to work. Here is the method ...

Ensure that the submission button also transmits an additional piece of information

My form has a submit button that sends field values to the address bar, but I want it to also add an extra value (&submitted=yes) when clicked. How can I modify my submit button from this: <input type="submit" name="submitted" value="submit"> ...

Connecting JSON objects based on unique GUID values generated

I am in search of a method to automate the laborious task of linking multiple JSON objects with random GUIDs. The JSON files are all interconnected: { "name": "some.interesting.name", "description": "helpful desc ...

Creating a box that is connected by lines using JSON data requires several steps. You

I am attempting to dynamically draw a line using the provided JSON data. I have heard that this can be easily achieved with flexbox. Important: I would greatly appreciate a solution involving flexbox This is what I hope to achieve: https://i.stack.imgu ...

Capture a snapshot of a Bootstrap modal using JavaScript

var takeScreenShot = function(){ html2canvas(document.body, { onrendered: function(canvas) { var tempcanvas=document.createElement('canvas'); tempcanvas.width=1350; tempcanvas.height=1350; var context=tempcan ...

Laravel implementation of Bootstrap Datepicker

Incorporating Laravel bootstrap and a date picker, I have encountered an issue where the todayHighlight feature is not functioning correctly. Additionally, the container aspect is also not working as intended. <link rel="stylesheet" href="https://sta ...

Having difficulty placing a marker using google-maps-react

import {Map, GoogleApiWrapper} from 'google-maps-react' var React = require('react') class GoogleMapContainer extends React.Component { render() { return( <Map google={this.props.google} sty ...

When using Material-UI's <Table/> component, an error is thrown stating that the element type is invalid

Struggling with material-ui Table is not familiar territory for me, especially since I have used it in numerous projects before. Currently, I am utilizing @material-ui/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="33505c41567 ...

"The Material UI date picker is encountering an issue with the error prop, which is being evaluated

I have developed a date picker that utilizes the Jalali calendar. While attempting to pass error checking using the error prop in the following code: <LocalizationProvider dateAdapter={AdapterJalali}> <MobileDatePicker label={lab ...

JQuery Function for Repeatedly Looping through Div Elements

I've been experimenting with creating a loop that alternates the fade-in and fade-out effects for different elements. This is what I have so far: setInterval(function() { jQuery(".loop").each(function(index, k) { jQuery(this).delay(1200 ...