I'm trying to use the below code to get the element located at the cursor's position, but the element is within an iframe. I thought the below code was supposed to get the deepest child element at the cursor's position, but it doesn't seem to do anything. What am I doing wrong?
When the page loads, I'm trying to click the "add one of everything to my cart" button.
from selenium import webdriver
from tkinter import *
from pynput import mouse
from pynput.mouse import Listener
def CheckRightClick(x, y, button, pressed):
if button == mouse.Button.right:
if pressed:
click_window.event_generate("<<quit>>")
print('Getting element')
element_at_cursor_script = 'return document.elementFromPoint(' + str(x) + ',' + str(y) + ');'
element = driver.execute_script(element_at_cursor_script)
print('Element at cursor is ', element)
options = webdriver.ChromeOptions()
driver = webdriver.Chrome(options=options, executable_path=r'C:\Users\David\Desktop\Python\chromedriver_win32'
r'\chromedriver.exe')
url = 'http://store.cardsagainsthumanity.com/'
driver.get(url)
click_window = Tk()
click_prompt = Label(click_window, text='Right click somewhere')
click_prompt.grid(row=0, column=0)
click_window.bind("<<quit>>", lambda *args: click_window.destroy())
listener = Listener(on_click=CheckRightClick)
listener.start()
click_prompt.mainloop()
listener.stop()
You must switch the driver context to the frame in order to interact with elements in that frame. In C# it's RemoteWebDriver.SwitchTo().Frame();
sorry, I don't know what it looks like in Python, you'll need to dig into the docs.
See if this works:
driver.SwitchTo().Frame(driver.FindElement(By.xpath(".//iframe[@title='Cart']")));
driver.FindElement(By.xpath(".//a[text()='Add one of everything to my cart.']")).click();
You can use the driver to go directly to the iframe url, just copy it from the iframe that comes up and you can access it directly rather than through a pop-up box.
driver.get('iframe.url')
driver.find_element_by_css_selector('iframeselector').click()
rather than
driver.get('website.url')
driver.find_element_by_css_selector('selector').click()
#click button that opens iframe
driver.find_element_by_css_selector('iframeselector').click()
This makes elements a lot easier to select via css selectors and I would recommend staying away from mouse coordination as scales vary from device-to-device. . Sincerely hope this helped. . PS Try to use css selectors rather than xpath where you can as it is normally more versatile (less buggy).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.