Automating button clicks with Python and Selenium (Updated for a different problem)

After encountering ad pop-ups on a previous mp3 converter site, I decided to try using an alternative website, h2converter.com/tr/, for my script. However, this time the web driver had trouble finding the button and the program stopped due to a timeout exception. To address this issue, I implemented xpath in my script to locate the button accurately. Here is the updated version of my code:

driver = webdriver.Chrome(executable_path="C:\chromedriver.exe")
driver.get("https://h2converter.com/tr/")
element = driver.find_element_by_name("video")
element.send_keys("https://www.youtube.com/watch?v=ZobdNXT0Za0", Keys.ENTER)

downloadElem=WebDriverWait(driver, 
60).until(EC.presence_of_element_located((By.XPATH,"//*[@id=download']")))
downloadElem.click()

As someone new to Selenium, I am working on a script to automate the download process of converted MP3 files. Despite my use of driver.find_element_by_css_selector, I keep receiving a NoSuchElementException error. I have tried various solutions suggested in other posts without success. How can I overcome this challenge? Below is the current version of my code:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Chrome(executable_path="C:\chromedriver.exe")

driver.get("https://www.onlinevideoconverter.com/mp3-converter")

element = driver.find_element_by_name("texturl")
element.send_keys("https://www.youtube.com/watch?v=ZobdNXT0Za0", Keys.ENTER)
driver.find_element_by_css_selector("download-button").click()

Answer №1

Two issues are present in this scenario: (1) the button is not specified correctly; and (2) the browser is not given time to wait for the button to appear.

Correctly Specifying the Button

In this case, the download-button should be referenced as class="download-button". When specifying a class in CSS selectors, it must be prefixed with a dot ., like so:

driver.find_element_by_css_selector("<b>.</b>start-button").click()
#                                    ^

Alternatively, you can use find_element_by_class_name(..):

# No dot prefix
driver.<b>find_element_by_class_name</b>("start-button").click()

Implementing a Wait Strategy

Since the button may not immediately appear, we need to introduce a wait time before locating it. One way to do this is by utilizing time.sleep(..). Here's how you can modify the script:

<b>from time import sleep</b>

from selenium import webdriver
from selenium.webdriver.common.keys import Keys


driver = webdriver.Chrome(executable_path="C:\chromedriver.exe")

driver.get("https://www.onlinevideoconverter.com/mp3-converter")

element = driver.find_element_by_name("texturl")
element.send_keys("https://www.youtube.com/watch?v=ZobdNXT0Za0", Keys.ENTER)

<b>sleep(5)</b>
driver.find_element_by_class_name("download-button").click()

Continuous Polling Approach

The previous approach involved waiting for five seconds regardless of when the button actually appears. To optimize this, we can implement a polling mechanism that continuously checks for the button:

<b>from time import sleep</b>

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
<b>from selenium.common.exceptions import NoSuchElementException</b>


driver = webdriver.Chrome(executable_path="C:\chromedriver.exe")

driver.get("https://www.onlinevideoconverter.com/mp3-converter")

element = driver.find_element_by_name("texturl")
element.send_keys("https://www.youtube.com/watch?v=ZobdNXT0Za0", Keys.ENTER)

<b>while True:</b>
    sleep(0.5)
    try:
        button = driver.find_element_by_class_name("download-button")
    except NoSuchElementException:
        pass
    else:
        <b>button.click()</b>
        break

Answer №2

It is necessary to wait for the download button to become visible before proceeding, which may take some time in your situation. You have two options:
1. Set a manual sleep delay:

time.sleep(max_seconds_wait)  

2. Wait for the download button to appear dynamically:

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


try:
    WebDriverWait(self.driver, delay).until(EC.presence_of_element_located((By.ID, 'downloadq')))
except:
      .....

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

Does the built-in waiting mechanism in Protractor automatically handle promises?

While browsing through Stack Overflow, I stumbled upon this response in a discussion about Protractor tests and asynchronous solutions: 'AFAIK expect waits internally for the related promises.' I have tried looking through the official Protract ...

Enhance your JavaScript code by replacing Promise syntax with Async syntax and utilizing map() instead of a traditional For

I have a code snippet here that is functioning properly. However, I am interested in converting the Promise code in the middle of the function to Async code and replacing the for loop with map(). Can someone guide me on how to achieve this transformation ...

Troubleshooting Timeout Problems with Selebiun Crawler in C#

I am encountering an error while running the following code. public void GetCategoriesSelenium() { string javascript = System.IO.File.ReadAllText(@"GetCategory.js"); CrawlerWebSeleniumJS.ExecuteScript("var finished;"); ...

Button click event is not being triggered by Ajax rendering

I am facing an issue with my Django template that showcases scheduled classes for our training department. Each item in the list has a roster button which, when clicked, should display the class roster in a div. This functionality works perfectly. However, ...

What is the best way to extract the singular PDF link from a webpage?

Currently, I am attempting to utilize Selenium in Java to access DOM elements. However, I have encountered an issue while testing the code: Exception in thread "main" org.openqa.selenium.StaleElementReferenceException: stale element reference: element is n ...

Obtain the text that is shown for an input field

My website is currently utilizing Angular Material, which is causing the text format in my type='time' input field to change. I am looking for a way to verify this text, but none of the methods I have tried give me the actual displayed text. I a ...

A guide on extracting the text content from an anchor tag by using xPath() with a combination of selenium and Mocha

I have successfully chosen an <a> tag. My goal is to display the text of the anchor tag, but I am facing difficulties. The technologies being used are selenium, mocha, javascript, and phantomJS This is the detailed script: var assert = require(&ap ...

Nightwatch execute() function not technique following anticipate

After reviewing the documentation, I am confident that this code should work correctly. However, I am encountering an issue where something needs to run once the expect has finished, but it doesn't seem to be functioning as expected. Functioning Code ...

"Exploring the World Wide Web with Internet Explorer Driver and Webdriver

After trying everything I know to make internet explorer work with webdriver.io, I've encountered a confusing issue. To start, download the internet explorer driver from this link: http://www.seleniumhq.org/download/. The file is an .exe named ' ...

Automating testing with JavaScript and Selenium WebDriver

Can testing be automated using the combination of JavaScript and Selenium? I am not familiar with Java, Python, or C#, but I do have expertise in Front-End development. Has anyone attempted this before? Is it challenging to implement? Are there any recom ...

I must interact with the video within the iframe by clicking on it

I am trying to interact with an iframe video on a webpage. Here is the code snippet for the video: <div class="videoWrapper" style="" xpath="1"> <iframe width="854" height="480" src="xxxxxxx" frameborder="0" allow="autoplay; encrypted-media" all ...

Guide on setting an attribute value with JavaScriptExecutor in Selenium WebDriver

I am attempting to set an attribute value for all instances of the same type of <img> tag on My website, for example: <img src="images/temp/advertisement.png"> and I want to set style="display: none" so that I can hide them. I have tried the ...

Error message stating that there is no property 'collection' in Firestore when using Firebase v9 modular syntax in Firebase Firestore

Working on a React application that makes use of Firebase Firestore for handling database operations, I recently upgraded to Firebase version 9 and adopted the modular syntax for importing Firebase services. Nevertheless, when attempting to utilize the co ...

Output a message to the Java console once my Selenium-created Javascript callback is triggered

My journey with Javascript has led me to mastering callback functions and grasping the concept of 'functional programming'. However, as a newcomer to the language, I struggle to test my syntax within my IntelliJ IDE. Specifically, I am working on ...

The PhantomJs browser is not able to open my application URL

Recently, my scripts in PhantomJS browser have stopped running. Whenever I try to capture screens, all I get are black screens. To troubleshoot this, I manually opened a URL in PhantomJS using the command window and ran the script below to verify if it ope ...

Exploring the capabilities of arrays within Ajax

Below is the original code I wrote in JavaScript: var wt_val = []; for (i = 0; i<human_wt.length; i++){ var mult; mult = data_list[basket_list[button_port_name][i]].map(x => x*(wt[i]/100)); wt_val.push(mult); ...

Selenium unable to interact with Javascript pop-up box

I am currently working on automating a feature for our web application, specifically a form of @mentioning similar to Facebook. On the front end, when a user types @ into a text input, the API is called to retrieve the list of users and display them in a b ...

Error: The session ID is not currently active

I encountered a problem with my tests failing when running them on TFS, showing the following error: WebDriverError: No active session with ID Failed: No active session with ID Interestingly, these same tests are passing locally. Everything was working ...

Is there a dependable resource for mastering Protractor along with the Jasmine Framework in Eclipse using JavaScript?

Starting a new role at my organization where I will be testing Angular JS applications. Can anyone recommend a good website for learning PROTRACTOR with JAVASCRIPT using the JASMINE Framework? (Would prefer if it includes guidance on Eclipse IDE) Thank yo ...

What is the best way to duplicate an entire webpage with all its content intact?

Is it possible to copy an entire page including images and CSS using Selenium? Traditional methods like ctrl + a or dragging the mouse over the page do not seem to work. How can this be achieved with Selenium without requiring an element to interact with? ...