Home > Blockchain >  How can I use the inside of the #document on a website, with selenium, to click on buttons?
How can I use the inside of the #document on a website, with selenium, to click on buttons?

Time:01-15

I have been trying to automate a game I found by clicking buttons with selenium, however in doing so I found troubles in getting past the iframe and #document.

Here is the game I'm trying to automate: This is the button I'm trying to access in the code, I cant figure out how to get selenium to call it though

I want to access a button on the website to start the game, but I cannot access this button. I have tried switching frames, I don't know if that worked but I think there are nested html files?

My ultimate goal is to be able to click on the buttons automatically, thanks for any help!

Here is the current code:

    # Store iframe web element
iframe = driver.find_element(By.CSS_SELECTOR, "#desktopGame > iframe")

    # switch to selected iframe
driver.switch_to.frame(iframe)

    # Now click on button
#driver.find_element(By.TAG_NAME, 'PlayChevrons').click()

driver.find_element(By.ID, "main").click()


d = driver.find_element(By.TAG_NAME, "use")

button = driver.find_element_by_xpath("//use[@href='#PlayChevrons']")
button.click()

button = driver.find_element_by_xpath("//use[@href='#PlayButton']")
button.click()

CodePudding user response:

The Play button is inside svg > g tags, you have to handle the elements inside svg or g tags like below:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

wait = WebDriverWait(driver, 15)
wait.until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR, "#desktopGame > iframe")))

time.sleep(1)
driver.find_element(By.XPATH, "//*[name()='svg']//*[local-name()='g' and @id='main']//*[local-name()='g' and @cursor='pointer']").click()

You can refer the below links to know how to handle svg and g tags:

https://medium.com/illumination/automating-svg-elements-with-selenium-a7c31f99ebf8

https://www.linkedin.com/pulse/designing-xpath-svg-elements-suresh-dubey/?trk=public_profile_article_view

https://www.tutorialspoint.com/clicking-on-elements-within-an-svg-using-xpath-selenium-webdriver#:~:text=New Selenium IDE&text=To click the element with,the build and execute methods.

  • Related