Python and Selenium, Trying to accept cookies on website results: Unable to locate element

Question:

I’m trying to enter a website with python (selenium) code and I’m required to accept cookies. For some reason, no matter what I’ve tried, I always get the result: Unable to locate element. Below ‘accept cookies button’ from the website’s HTML code.

<button tabindex="0" title="Hyväksy kaikki evästeet" aria-label="Hyväksy kaikki evästeet" class="message-component message-button no-children buttons-row" path="[0,3,1]">Hyväksy kaikki evästeet</button>

I’ve tried the following:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from time import sleep
import pandas as pd 
import requests as req

class trackerBot(): 
        
    def __init__(self):
        self.driver = webdriver.Chrome()
        # Tried with and without implicitly wait
        self.driver.implicitly_wait(10)
            
    def loadWebsite(self, uri):
            
        self.driver.get(uri)
        cookies_accept_btn = self.driver.find_element_by_xpath('/html/body/div/div[3]/div[5]/button[2]')
        cookies_accept_btn.click()
                
def main():
    bot = trackerBot()
    bot.loadWebsite("https://www.tori.fi")        
    return(0)
    
main()

Can someone advise what I’m missing?
Many thanks in advance!

Asked By: Böhmeli

||

Answers:

Try this in find_element_by_xpath ("//button[@title=’Hyväksy kaikki evästeet’]")

if this can not overcome your issue than take reference from this site:

https://devhints.io/xpath

Answered By: Black
WebDriverWait(self.driver, 10).until(EC.element_to_be_clickable((By.XPATH,"//button[@title='Hyväksy kaikki evästeet']"))).click()

Use a Webdriver wait for the element and find the element by xpath with it’s data-attribute title.

Import

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait 
from selenium.webdriver.support import expected_conditions as EC
Answered By: Arundeep Chohan

The element may be in an iframe.
Use switch_to:
Switch to an iframe through Selenium and python

driver.switch_to.frame(iframe)
Answered By: DMart

The ‘accept cookies window’ was in the iframe so I had to switch to that frame to be able to locate the element. Switching done with following code:

iframe = self.driver.find_element(By.XPATH, '//iframe[@id="sp_message_iframe_433571"]')

self.driver.switch_to.frame(iframe)

This answer was posted as an edit to the question SOLVED Python and Selenium, Trying to accept cookies on website results: Unable to locate element by the OP Böhmeli under CC BY-SA 4.0.

Answered By: vvvvv
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.