Unable to interact with a button through JavaScript using execute_script in Selenium

https://i.stack.imgur.com/hJmtK.png I am attempting to remove a cookies popup by accepting the cookies and clicking confirm. While I am able to click an input labeled "zgadzam się na", for some reason, clicking a button with the label "potwierdź" appears to be impossible. Here is the snippet of my code:

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

auction_url='https://www.g2a.com/grand-theft-auto-v-rockstar-key-global-i10000000788017'

driver = webdriver.Chrome()

driver.get(auction_url)

add_popup = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.XPATH, '//*[@id="webklipper-publisher-widget-container-notification-frame"]'))
)

driver.switch_to.frame(driver.find_element_by_xpath('//*[@id="webklipper- 
publisher-widget-container-notification-frame"]'))
print('ads popup detected')
time.sleep(1)
driver.find_element_by_xpath('//*[@id="webklipper-publisher-widget- 
container-notification-close-div"]').click()
print('ads popup closed')
driver.switch_to.default_content()

driver.execute_script("document.querySelector('#cookies-select-all').click();") # this works fine
time.sleep(3)
driver.execute_script("document.querySelector('body > div:nth-child(76) > div > div > div > div > div.modal-options__buttons > button.btn.btn-primary').click();") # however, this throws an error

The error message that I encounter is as follows:

selenium.common.exceptions.WebDriverException: Message: javascript error: Cannot read property 'click' of null

An interesting observation is that when I run this JavaScript code in the browser's console directly, it does not generate any errors.

Answer №1

Here is the code that worked perfectly for me:

driver.execute_script("document.querySelector('body > div:nth-child(60) > div > div > div > div > div.modal-options__buttons > button.btn.btn-primary > span').click();")

Alternatively, you can try this code to locate the element:

driver.find_element_by_css_selector("div.modal-window button.btn-primary").click()

Answer №2

Upon further exploration, I stumbled upon the revelation that this particular website generates an excessive number of

<div class="ReactModalPortal"></div>
. I had been utilizing div:nth-child(x), where x represented a constantly changing and peculiar quantity of empty divs. Due to my x being fixed, my selection process was flawed...

Fortunately, a remedy surfaced:

driver.execute_script("document.getElementsByClassName('modal-options__buttons')[0].getElementsByTagName('button')[0].click()")

Answer №3

Why settle for

driver.execute_script("document.querySelector('body > div:nth-child(76) > div > div > div > div > div.modal-options__buttons > button.btn.btn-primary').click();")#error

When you can try clicking the button using a CSS Selector.

WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.CSS_SELECTOR,'button.btn.btn-primary span'))).click()

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Python 2: Exploring the differences between a Unicode object and a string object

I came across this issue on StackOverflow, but I was unable to find a satisfactory solution: The problem I am facing involves comparing Unicode strings received from a server with hardcoded strings in my code. Even though I understand why a simple == comp ...

What is the equivalent of getElementById in .ts when working with tags in .js?

Looking to incorporate Electron, Preload, Renderer with ReactJS and TypeScript into my project. <index.html> <body> <div id="root" /> <script src='./renderer.js'/> </body> <index.ts> const root = Re ...

Leveraging the power of Framer Motion in combination with Typescript

While utilizing Framer Motion with TypeScript, I found myself pondering if there is a method to ensure that variants are typesafe for improved autocomplete and reduced mistakes. Additionally, I was exploring the custom prop for handling custom data and des ...

In Vue.js, I only want to retrieve and display the parent's ID or name once for each of its child components

<td v-if="currentId != loop.id" class="text-center"> <div :set="currentId = loop.id">{{ loop.id }}</div> </td> <td v-else></td> Looking to achieve a specific layout like this This invo ...

Steps for creating a while loop that continuously inputs prices until the user enters 0:

I am hoping to create a simple Python code that allows users to input prices from a shopping trip, with the loop ending when they input 0. Once the loop stops, I'd like to display the total number of items, average price, and total price using an else ...

Navigate to a different page in NextJs without causing a page refresh or altering the current state of the application

Recently, I encountered a challenge in my NextJS application while attempting to incorporate dynamic routes as endpoints on my server. Specifically, when accessing localhost:3000/register, the register.tsx file is loaded successfully. However, within one ...

Display various child components in a React application depending on the current state

I'm currently developing a brief React quiz where each question is represented as an independent component. I aim to swap out the current question component with the next one once a question is answered. Here's the present state of my root compon ...

Issue encountered with Stylegan2-ada tfrecords: ValueError due to mismatched axes in array causing images to function intermittently

Currently, I am in the process of training a GAN using Google Colab with a dataset of images sourced from Wikiart that have been converted to 1024x1024 resolution. However, I keep encountering an error when attempting to create the tfrecords: Traceback (mo ...

The function is coming back with a value of undefined

I need some assistance with a function I have below. This function is meant to download files one by one and move them to a directory called templates. At the end, it should return the length of the directory. However, it seems to be returning an undefined ...

I keep encountering the following error message: " ERROR Error Code: 200 Message: Http failure during parsing for http://localhost:3000/login"

My Angular Login component is responsible for passing form data to the OnSubmit method. The goal is to send form data from the front-end application and authenticate users based on matching usernames and passwords in a MySQL database. ***This login form i ...

Encountering issues when implementing react-router with the client-side library

After following the author's suggestion, I've successfully loaded the client-side library. The recommended method is to simply drop a <script> tag in your page and use the UMD/global build hosted on cdnjs. I have ensured that ReactRouter i ...

Create a CSS menu that centers the links

Here is the CSS code I am using for my horizontal menu: nav { height: 40px; width: 100%; background: #F00; font-size: 11pt; font-family: Arial; font-weight: bold; position: relative; border-bottom: 2px solid # ...

Verify if the button is assigned a specific class, then generate a 'completed' div

I'm new to working with Jquery and I have a question. In my upload form, when something is uploaded the upload-button changes class from: <a class="upload-button upload buy" id="upload-button"><span>Upload a document</span></a> ...

Retrieving the date input from a React form powered by Bootstrap

Is there a way to extract a specific timestamp in the format yyyy-mm-dd from the code snippet below? handleDateChange = e => {} <Form.Group as = {Col}> <Form.Control type = "date" value = { this.state.closingDate } onChange = { ...

Exploring alternative methods of iterating over the values in a key-value pair within an AngularJS framework

My key-value pair consists of a long list of file names stored in the variable $ctrl.displayData- 143:"/this/is/a/very/long/fil22↵/this/is/a/very/long/file/path.php↵anotherone.php↵newfilel123.php" When I use ng-repeat to display these file names, t ...

What is the best way to show a filtered list using a state that was created with useState in React?

Check out my code in CodeSandbox, consisting of 4 divs categorized as "Book" and "Article". There are buttons at the top to toggle between displaying all divs, only books, or only articles. However, clicking on any button currently shows all divs and gives ...

How the logo's placement shifts while zooming out (using CSS and Angular 4+)

I am facing an issue with my navbar that includes a logo (MostafaOmar) which shifts position when zoomed out. If you try zooming to 70%, you will notice the logo's position changes as well. Is there a way to make it stay in place at 100% zoom? Here ...

After configuring Python Selenium with a proxy, the message 'There are no active modal dialogs' is displayed

While using a proxy with my webdriver, an authentication dialog requiring user/pass credentials appears. To address this, I opted to utilize an autoit script for a simpler solution: #Include <File.au3> WinWaitActive("Authentication Required") Send( ...

How come it's not possible to modify the text of this button right when the function kicks off?

When I click a button, it triggers a JavaScript function. The first line of code within the function uses jQuery to change the HTML of the button. However, the button's text does not update in the browser until after the entire function has completed, ...

Unique column arrangement specifically designed for the initial row within the loop

My webpage features a layout that showcases 4 images on each row. However, I am looking to create a special first row with a unique column configuration compared to the rest of the rows. Here is an example of what I have in mind: This particular row will ...