Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get HTML element coordinates?

I was wondering if there is a way to get the coordinates of an HTML element in an HTML page without opening the page in the browser. I'm using python and I saw that you can pull some requests to get the HTML page and after that, you can search inside it using modules like bs4 but I didn't find a way to get the element coordinates, is that possible? (for element coordinates I mean the x pos and y pos of the element when the page is loaded by the broswer)

Let us say that I want to get the HTML text of this page and i have wrote this

import requests
from bs4 import BeautifulSoup

data = requests.get("https://www.nike.com")
soup = BeautifulSoup(data.text, 'html.parser')

element = soup.find('p',{'class':"vVtA7wL6 headline-sm-base text-color-primary-dark"})

print(element.coords) # exists/can I create in some way a module that returns the coords?

Is there a way to find the element.coords when the element is displayed in the browser?

like image 883
Mat.C Avatar asked May 25 '26 21:05

Mat.C


1 Answers

In general not possible, because coordinates depend on how exactly given browser renders it.

But you can open some browser in python, and run a javascript which retrieves coordinates and returns it to python. We will use pywebview as a browser (requires pip3 install pywebview).

Open browser window, use JavaScript to examine HTML element, return values, and close browser window. Note the values will depend on window size.

import webview
from threading import Thread


def thread_fun():
  while webview.evaluate_js('document.readyState') != "complete":
    # wait for page to load
    time.sleep(0.5)

  # ask for a bounding rect
  bounding_rect = webview.evaluate_js('''
    document.querySelector("img.central-featured-logo").getBoundingClientRect()
  ''');  
  webview.destroy_window()

  print(bounding_rect)


thread = Thread(target=thread_fun)
thread.start()

webview.create_window(title="a title", url="http://wikipedia.org", width=500, height=700)

thread.join()

Result: {'x': 150, 'y': 176, 'width': 200, 'height': 183, 'top': 176, 'right': 350, 'bottom': 359, 'left': 150}

webview.create_window must be called in main thread, it blocks it until window is destroyed.

For details on the webview package see https://pywebview.flowrl.com/

like image 155
user2622016 Avatar answered May 27 '26 09:05

user2622016



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!