Converting HTML Javascript to JAVA with the help of Selenium

Can someone help me extract the value of h1 as a string using selenium?

Check out the HTML javascript snippet below-

<script type="text/javascript">
    $(window).load(function() {    
        var $windowHeight = $(window).height() -12;
        $("#top").height($windowHeight);
        $('h1').css({
                'margin-top' : (($windowHeight) - $('h1').outerHeight())/2,
                'margin-bottom' : (($windowHeight) - $('h1').outerHeight())/2,
                'opacity' : '1.0',
                'filter' : 'alpha(opacity = 100)',
        });

        $("#container").click(function(){
            $("html, body").animate({ 
                scrollTop: $windowHeight + 50
            }, 1500);
        })

    });
    $(window).on("debouncedresize", function( event ) {
        var $windowHeight = $(window).height() -12;
        $("#top").height($windowHeight);
        $('h1').css({
                'margin-top' : (($windowHeight) - $('h1').outerHeight())/2,
                'margin-bottom' : (($windowHeight) - $('h1').outerHeight())/2
        });
    });
</script>

For extracting h1 value in JAVA, here is what I have so far-

WebDriver driver = new FirefoxDriver(); 
    driver.get("view-source:http://websitename.com/");
    Thread.sleep(3000);
    JavascriptExecutor js = null;
    if (driver instanceof JavascriptExecutor) {
        js = (JavascriptExecutor)driver;
    }
    js.executeScript("h1");

I'm not sure if JavaScriptExecutor is the right approach for this task. Any suggestions or guidance would be greatly appreciated. Thank you!

Answer №1

The h1 tag is an important part of a web page. Instead of using JavascriptExecutor to access it, you can easily retrieve the text of the h1 header using the following code:

String text = driver.findElement(By.css("h1")).getText();

If you need to get an attribute of the tag, you can use this code instead:

String attr= driver.findElement(By.css("h1")).getAttribute(<attr-name>);

Answer №2

Success! I managed to resolve the issue by utilizing driver.getPageSource(); instead of using driver.get("view-source:websitename.com/"). Silly mistake on my part. Grateful for the assistance! :)

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

Stripping CSS from my HTML using TinyMCE

I have created a custom Javascript function that retrieves the content of an HTML file from my server and then integrates it into a TinyMCE editor. Here is the function: function LoadTemplate(url) { $.post(url, function (data) { // Access the ...

Download a file on button click using JavaScript with data extracted from the DOM

I am looking to create a download feature where a user can click a button on the webpage, triggering a JavaScript method to capture the contents of a DOM element and prompt the user for a download. After successfully capturing the DOM element in a JavaScr ...

Searching for email addresses across multiple Google websites in Python

Currently, I am in the process of sourcing email addresses for various companies by conducting online searches. Using an Excel file that contains a list of company names, I crafted a script to automate this task. The script is designed to search each comp ...

Guide for registering to modifications of a single key within a form group in Angular 2

I am facing an issue with my userForm group that consists of keys name, email, and phone. I have implemented an onValueChanged function to validate these fields whenever they are changed. However, the validation runs every time even if the field has not ...

How can I make multiple elements change color when hovering with CSS?

Hey there! I have a little design challenge that I need help with. On my website (), I am trying to make multiple elements of a specific item change color when the user hovers over the text. If you hover over the "more" menu item, you'll notice that o ...

Enhance the FirefoxDriver functionality to automatically scroll to a specific element on

I have encountered a challenge while working on a page that features a small frame at the top. This is causing some difficulties when the firefoxdriver attempts to scroll to a specific element, as it tends to position the element at the very top of the pag ...

What could be causing the data storage issue in the state?

Using axios, I am fetching data and storing it in a state variable useEffect(() => { getCartItems(); }, []); const [abc, setAbc] = useState([]); const getCartItems = async () => { let data = await CartApi.get(`/${store.getState().auth.user.id}/ ...

How can I manage excessive amounts of data in a single line and prevent overwhelming the system?

The title may be a bit confusing, but what I am trying to convey is: InputStream is = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; JSONArray ja = new JSONArray(); wh ...

issues with jasmine angularjs tests exhibiting erratic outcomes

During the execution of my unit tests, I often encounter a scenario where some random test(s) fail for a specific controller without any apparent reason. The error messages typically look like this: Expected spy exec to have been called with [ Object({}) ...

Are there any AJAX tools or packages in Node.js Express for connecting (posting/getting) with other servers and retrieving data?

Can someone please guide me on how to utilize ajax in node.js to send and receive JSON data from another server? Is there a package available that allows for this functionality, similar to jQuery's $.ajax, $.post, or $.get methods? ...

Tips for preventing the playback of the sound while recording

When creating a basic JavaScript application that involves opening a stream from the user and analyzing frequencies, I found that while Google Chrome and Opera work well by providing feedback in the headphones, Firefox often remains silent. Additionally, F ...

"Implementing a feature in React JS react-table to dynamically add a new column when a

I'm struggling to add a new column to react-table when a button is clicked. Even after re-rendering the table with a flag, I can't seem to add the new column. Can anyone suggest where I might be going wrong? Here's the link to the executable ...

Axios fails to input data into the table

Having trouble with my axios request to insert.php. The variable note_text is coming back as null. I suspect it's because I'm not properly specifying the 2nd argument. My assumption was that there would be a variable like $ _POST['note_text ...

Angular tutorial: Organizing data by date only

This is my first time building an Angular app. I am fetching JSON data from an API using a factory service to get football match fixtures. My goal is to group these fixtures by date while disregarding the time component. The date string in the JSON is fo ...

Is it possible to make this functionality Angular-friendly?

I am in the process of transforming a Bootstrap + jQuery theme into Angular JS, and I am encountering some challenges along the way. One issue is related to the functionality provided in the JS file of the theme: /* Sidebar Navigation functionality */ var ...

Displaying MySQL information on an EJS document including references to other tables

Check out the project on GitHub I am currently working on retrieving quiz answers from a MySQL database and displaying them in a form using EJS templating within a node.js/express application. However, I am facing challenges with correctly mapping answers ...

Why is only the last element's value displayed when printing a Java array?

Looking to keep my coding skills sharp, I decided to create a simple program that would display the values of an array based on two different variables provided. I anticipated to see each value printed on the screen, but to my surprise, only the final ele ...

Having issues with JavaScript and MySQL data retrieval following XMLHttp update to the database

After running the newNet.php file successfully creates a new entry and assigns it an auto-incremented netID. The next step is to retrieve this newly created ID and use it in the showActivities() function to display the record. Ideally, it should work like ...

Which Browser (or version) is the Only One That Cannot Manipulate Flash Objects?

In my attempts to modify Flash Objects / Embeds using Javascript, I've found that it works in all browsers except for IE. This has led me to consider abandoning IE altogether for this application, unless there are other older or less used browsers tha ...

Ways to choose an element when all classes are identical but the text content varies?

I'm looking to automate the website, specifically by selecting the Widgets section and clicking on it. The issue is that all the cards have the same class name, only the text inside them differs. I tried using this code snippet: get getWidgetButton() ...