Mandar Sadye
Mandar Sadye

Reputation: 689

How to use Selenium to find location of element in webpage?

I am trying to find the location of the element by ID on a webpage using Selenium.But the problem is that when I run python code I get the wrong location of the element. Following image illustrates the problem I am facing.In the picture yellow circle shows the element with ID 'ca-talk' and red circle shows the location which I get after running the script. enter image description here

the code is as follow:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException
from datetime import datetime
import pyautogui
import os
from collections import OrderedDict
import urllib.request
from pathlib import Path
from requests import get
import time

minimumWindow = False

def internet_on():
    i = 0
    while True:
        try:
            urllib.request.urlopen('http://www.google.com', timeout=20)
            return True
        except:
            print("Internet not found for last %s minuts" % i)
            i = i + 1
            time.sleep(60)
            pass

browser = webdriver.Chrome()
browser.maximize_window()
if minimumWindow:
    pyautogui.moveTo(600, 3, 1)
    pyautogui.dragTo(0, 200, 1, button='left')

browser.get('https://en.wikipedia.org/wiki/Main_Page')

e = browser.find_element_by_id('ca-talk')
location = e.location
size = e.size
print(location)
print(size)
pyautogui.moveTo(location['x'], location['y'], 0.1)

(x, y) = pyautogui.position()

print(str(x) + " " + str(y) + "\n")

the output is as follow:

{'x': 254, 'y': 40}
{'height': 40, 'width': 38}
254 40

while actual location is around x = 335 and y = 205.

Any idea why this may be happening. Thank you

Upvotes: 2

Views: 2853

Answers (1)

Mandar Sadye
Mandar Sadye

Reputation: 689

After many trial and error, I found the solution.

pyautogui.moveTo(location['x'], location['y'], 0.1)

All need to be done is that this line is to be replaced by

a = browser.execute_script("return outerWidth")
c = browser.execute_script("return outerHeight - innerHeight")
b = browser.execute_script("return outerHeight")
pyautogui.moveTo(location['x']*1920/a, (location['y'] + c)*1080/b, 0.1)

here 1920 and 1080 is my screen resolution.

I found that for some reason the value return by outerWidth and outerHeight are not equal to 1920 and 1080 respectively and thus the ratio 1980/a and 1080/b gives multiplying factor to get original pixels.While the c takes care of space wasted in url bar and other things that are not part of a webpage.Here x and y location is location with respect to webpage not screen.

If someone has any idea why outerWidth and outerHeight are not equal to 1980 or 1080 then I would like to read. Thank you.

Upvotes: 1

Related Questions