3

I need to be able to gather the active CSS and HTML attributes of an element given the URL and XPath of the element as parameters. For example, if I give the XPath of the "Ask Question" button on https://stackoverflow.com, I would like the program to be able to tell me that it is 100.11 x 37.78 pixels, is an html link to /questions/ask, is colored rgba(102,191,255,0.75), etc.

I've been told jokingly that I might need to make an entirely new browser to do this; is that true? Is there a way to do this?

Does any language have a library to do this? I know about Beautiful Soup for python but I can only seem to get the HTML code, without CSS.

1 Answers1

0

Well, since nobody has answered your question in 2 years in 7 months, I might as well waste my time and answer it for future visitors.

The answer to your question is quite simple, but it requires multiple parts. You can use JavaScript to do this and you could have easily searched for what you wanted before asking this question. Let's start with getting the height and width of an element (example: How do I retrieve an HTML element's actual width and height?). To get the height and width of an element, element.getBoundingClientRect(). The code I'm using here is written so it's easy to understand, but it can be compressed a lot more than it is.

// get element foo from the page
var foo = document.getElementById("foo");
var fooRect = foo.getBoundingClientRect();
// print measurements
console.log("Width: " + fooRect.width);
console.log("Height: " + fooRect.height);

Getting styles is once again pretty easy, and you could have also easily searched this answer as well (example: Get all css styles for a DOM element (a la Firebug)). You can use window.getComputedStyle(element) to get all CSS styles and then nitpick through what you want using simple array methods. The method mentioned will return the styles in terms of px

// get element bar from the page
var bar = document.getElementById("bar");
var barCSS = window.getComputedStyle(bar);
// print all CSS values
for(let i = 0; i < barCSS.length; i++){
    // from the linked answered question
    console.log(barCSS[i] + "=" + barCSS.getPropertyValue("" + barCSS[i]);
}