How to mouse over with Python Selenium 4.3.0?

Viewed 26

ENV

Python 3.10 Selenium 4

Hi,

I use :

def findAllByXPath(p_driver, xpath, time=5):
try:
    #return WebDriverWait(p_driver, time).until(EC.presence_of_all_elements_located((By.XPATH, (xpath))))
    return WebDriverWait(p_driver, time).until(EC.presence_of_all_elements_located((By.XPATH, xpath)))
except Exception as ex:
    print(f"ERROR findAllByXPath : {ex}")

posts = findAllByXPath(p_driver,"//article//a",2)
for index in range(0,len(posts)):
    
    p_driver.execute_script("arguments[0].scrollIntoView()", posts[index])
    time.sleep(random.uniform(0.5, 0.8))
    action.move_to_element(posts[index]).perform()

To make a mouse over and try to get elements. I am trying to get the number of comments on an Instagram post from a page profile. If you pass manually the mouse over a post, the number of comments or likes is displayed. But when I try to do it in python, it doesn't find the element. I tried the XPath from console $x(//article//li//span[string-length(text())>0]")

It gives results when I freeze the browser with F8. action.move_to_element(post).perform() doesn't work? I suspect this version 4.3.0 removed many functions like ActionChains from the Selenium version 3, didn't it? How can I extract this element?

Or Am I doing something wrong?

1 Answers

ActionChains works nicely in Selenium v4!
I don't have an Instagram account so I cannot try there but you can see by running this code that move_to_element() works and how it works.
The About button (top left corner of stackoverflow homepage) get highlighted.
Remember to don't move your mouse while running of course!

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

driver = webdriver.Firefox()
actions = ActionChains(driver)
driver.get("https://stackoverflow.com/")
about_button = WebDriverWait(driver, 30).until(EC.visibility_of_element_located((By.XPATH, "//a[@href='https://stackoverflow.co/']")))
actions.move_to_element(about_button)
actions.perform()

EDIT: I am using Selenium 4.4.3 and Python 3.10 but it should work with Selenium 4.3.0 as well.

Related