Reputation: 59
I am trying to click a 'next' button with Selenium in Python, which source code is:
<div class="form-group clearfix">
<button id="experiment-method-previous" type="button" class="btn btn-dark pull-left" ng-click="navigate('run',$event)">Previous</button>
<button id="experiment-method-next" type="button" class="btn btn-primary pull-right" ng-click="navigate('export',$event)">Next</button>
</div>
I use the line:
driver.find_element_by_id('experiment-method-next')
but I get this error:
Unable to locate element: [id="experiment-method-next"]
Same for
driver.find_element_by_class_name('btn btn-primary pull-right')
Unable to locate element: .btn btn-primary pull-right
Any thoughts?
Upvotes: 1
Views: 124
Reputation: 59
The solution I found is to kill first any previous windows my application opens and switch to the latest one:
current_window = driver.window_handles[1]
driver.switch_to_window(current_window)
Now, the Next Button can be clicked as follows:
driver.find_element_by_id('experiment-method-next').click
()
Many thanks to the users Andrei Suvorkov and DebanjanB for their help.
Upvotes: 1
Reputation: 193388
As per the HTML you have shared to invoke click()
on the element with text as Next you have to induce WebDriverWait for the desired element to be clickable and you can use either of the following solution:
CSS_SELECTOR
:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button.btn.btn-primary.pull-right#experiment-method-next"))).click()
XPATH
:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@class='btn btn-primary pull-right' and @id='experiment-method-next']"))).click()
Note : You have to add the following imports :
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
Upvotes: 2
Reputation: 5647
I think your elememnt is inside frame/iframe
. To be able to interact with elements inside frame/iframe
you have to switch to it's content like this:
WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH, "//path_to_frame")))
then you can locate your element and interact with it:
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, "experiment-method-next"))).click()
and when you are done with content inside frame
, you have to switch back to default content:
driver.switch_to.default_content()
Note: you have to do some imports:
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
PS: if your elements is not inside frame, then just use WebDriverWait
:
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, "experiment-method-next"))).click()
this will wait at least 10 seconds until element will be clickable and the clicks on it. Hope this helps.
Upvotes: 1