How can i use slenium in Python to click the button? - python

I try to find how can I click on button for accept cookies with a python in selenium,
I used a lot of convinations but nothing works :(
This is the element:
<button class="button primary cookie-button" ng-click="$ctrl.allowAllCookies()">
<span class="ng-binding">Todas las cookies</span>
</button>
I used in other with:
wait = WebDriverWait(driver, 5)
time.sleep(2)
wait.until(EC.presence_of_element_located((By.ID, "onetrust-banner-sdk")))
element = wait.until(EC.element_to_be_clickable((By.XPATH, '//*[#id="onetrust-accept-btn-handler"]')))
element.click()
This is all the code from button:
<div class="text-center cookie-controls"> <button class="button primary cookie-button" ng-click="$ctrl.allowCookiesSelection()"> <span class="ng-binding">Permitir selección</span> </button> <button class="button primary cookie-button" ng-click="$ctrl.allowAllCookies()"> <span class="ng-binding">Todas las cookies</span>
But now I don't have id to use and I don't know how can I use.

Accordingly to XML you presenting in the question you can locate this button with several XPath locators.
For example try this:
wait = WebDriverWait(driver, 20)
wait.until(EC.element_to_be_clickable((By.XPATH, '//button[contains(#ng-click,"allowAllCookies")]'))).click()

Related

Selenium click button with <a> tag - intercepted exception

I am trying to click a button on a website in Python using Selenium. The html for the button I want looks like this:
<a onclick="exportGridExcel()"><span class="accordion-download"><i class="fa fa-file-excel-o" title="Download Excel" aria-hidden="true"></i></span></a>
A more expanded version of the html is:
<div class="lang-switch-wrapper lang-switch-inverse-wrapper">
<div class="lang-switch">
<ul>
<li class="dropdown">
<a href="#" class="dropdown-toggle lang-lable" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
<span class=" hidden-xs">English</span>
<span class="hidden-lg hidden-md hidden-sm">EN</span>
<img src="/etc/designs/wbrrdesign/clientlibs-wbrredsign/img/angle-down-gray.svg" alt="dropdown"></a>
<ul class="dropdown-menu dropdown-item">
<li>Español</li>
</ul>
</li>
</ul>
</div>
</div>
Then some other stuff before going to the button group and button I want:
<div class="button-group">
<button onclick="onModifyQuery()" type="button" class="btn">Modify Query</button>
<a onclick="exportGridExcel()"><span class="accordion-download"><i class="fa fa-file-excel-o" title="Download Excel" aria-hidden="true"></i></span></a>
<a title="Undo to column removal" onclick="restoreColumn()" class="toggle-btn primary-light-blue-btn"><i class="fa fa-circle-o-notch" aria-hidden="true"></i></a>
</div>
Part of my confusion is inexperience with this html with multiple classes and "i class".
EDIT:
If I try something like:
WebDriverWait(driver,300).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a[onclick='exportGridExcel()']"))).click()
Then I get the error:
ElementClickInterceptedException: element click intercepted: Element <a onclick="exportGridExcel()">...</a> is not clickable at point (772, 11). Other element would receive the click: <div class="lang-switch-wrapper lang-switch-inverse-wrapper">...</div>
The problem is that your page is automatically scrolled up and the excel download button is probably hidden by the top banner that contains the language selector. When Selenium tries to click on the excel download button, it finds the language selector instead.
I would suggest you to scroll the page up till the whole data table is visible
You can use something like this. Press HOME key to go to top of the page
from selenium.webdriver.common.keys import Keys
...
...
element = WebDriverWait(driver,300).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a[onclick='exportGridExcel()']")))
element.send_keys(Keys.CONTROL + Keys.HOME)
element.click()
Ideally clicking on the element <a onclick="exportGridExcel()"> as per your code trials inducing WebDriverWait for the elementToBeClickable() should have worked.
However, there seems to be a decendant <span>. So you can use either of the following locator strategies:
Using CSS_SELECTOR:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a[onclick^='exportGridExcel'] > span.accordion-download"))).click()
Using XPATH:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[starts-with(#onclick, 'exportGridExcel')]/span[#class='accordion-download']"))).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
In another approach you can also use JavascriptExecutor as follows:
Using CSS_SELECTOR:
element = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a[onclick^='exportGridExcel'] > span.accordion-download")))
driver.execute_script("arguments[0].click();", element)
Using XPATH:
element = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[starts-with(#onclick, 'exportGridExcel')]/span[#class='accordion-download']")))
driver.execute_script("arguments[0].click();", element)

Problem finding button with Selenium on Python (not working)

I have the next code for a button, but I can't find it (to click it) with Selenium:
<button class="practice-button btn btn-primary btn-large theme-primary-button">OK, I'm ready! </button>
I've tried with
browser.find_element_by_xpath("//button[#class='practice-button btn btn-primary btn-large theme-primary-button']")
browser.find_element_by_class_name('practice-button btn btn-primary btn-large theme-primary-button')
browser.find_element_by_class_name('practice-button')
but none of them has worked. Can you help me, please?
Here is what I tried for finding a button with given classes and it worked. Depending on the context, there may be more efficient ways to find the button. Feel free to share the url or page code.
xpath
class_name
css_selector
Given the page is as follows:
<!DOCTYPE html>
<body>
<button class="practice-button btn btn-primary btn-large theme-primary-button">OK, I'm ready! </button>
</body>
</html>
from selenium import webdriver
driver = webdriver.Chrome()
driver.get('file:///Users/jabbson/Projects/python/selenium-test/index.html')
button1 = driver.find_element_by_xpath('''//button[contains(#class, 'practice-button') and
contains(#class, 'btn') and
contains(#class, 'btn-primary') and
contains(#class, 'btn-large') and
contains(#class, 'theme-primary-button')]''')
button2 = driver.find_element_by_class_name('practice-button')
button3 = driver.find_element_by_css_selector('button.practice-button')
print('xpath:', button1.text)
print('class_name:', button2.text)
print('css_sel:', button3.text)
outputs:
xpath: OK, I'm ready!
class_name: OK, I'm ready!
css_sel: OK, I'm ready!

Selecting button without ID in selenium Python

I'm learning with Python Selenium and I'm trying to click a button which doesn't seem to have an id. I get an error that the element could not be scrolled into view.
Could anyone help with how I click the element?
It might be useful to know that the button only appears when you mouse over a section of the page
HTML is:
<div class="btn-group" role="group" aria-label="...">
<button type="button" class="grey-bg btn btn-default btn-expand" title="Expand"></button>
<button type="button" class="grey-bg btn btn-default btn-export" title="Export"></button>
<button type="button" class="grey-bg btn btn-default btn-clone" title="Clone"></button>
<button type="button" class="grey-bg btn btn-default btn-stamp" title="Pin"></button>
<button type="button" class="grey-bg btn btn-default btn-delete" title="Delete"></button>
</div>
I've tried to select by xpath:
driver.find_element_by_xpath('//*[#title="Export"]').click()
Thanks!
As you mentioned, it appears when you mouse hover. Kindly refer to this discussion for mouse hover. And try to look for the button after then click using javascript as this doesn't need to be displayed in order to click.
exportBtn = driver.find_element_by_xpath('//*[#title="Export"]') driver.execute_script("arguments[0].click();", exportBtn)
From the error, it looks like the element hasn't been scrolled into view. In order to scroll to the element, just add this line to ur code:
element = driver.find_element_by_xpath('//*[#title="Export"]')
driver.execute_script("arguments[0].scrollIntoView();", element)
element.click()
Hope that this helps!

How to find and click the button by "onclick" with Selenium and Python?

There are 2 buttons in a page, and the difference between these 2 buttons is "onclick".
<button class="btn btn-primary" style="width: 96px;" type="button" id="YesBtn" onclick="check_security('security_div0')">OK</button>
<button class="btn btn-primary" style="width: 96px;" type="button" id="YesBtn" onclick="check_security('wlan1security_div0')">OK</button>
I was thinking to use xpath:
driver.find_element_by_xpath("//form[#id='update-container-id']/div/div/div/div[2]/div/div[2]/table[1]/tbody/tr[1]/td[8]/div[3]/div/div/div/div[3]/button").click()
But it responses the error as below:
selenium.common.exceptions.ElementNotInteractableException: Message: Element <button id="YesBtn" class="btn btn-primary" type="button"> could not be scrolled into view
Does anyone can help me to click the 2nd button correctly? Thanks a lot.
try with the x-path //button[#onclick="check_security('wlan1security_div0')"]
driver.find_element_by_xpath("//button[#onclick=\"check_security('wlan1security_div0')\"]").click()
Using Action class,
button = driver.find_element_by_xpath("//button[#onclick=\"check_security('wlan1security_div0')\"]")
ActionChains(driver).move_to_element(button).click(button).perform()
using java script executor,
driver.execute_script("javascript:check_security('wlan1security_div0')")
As per the HTML you have provided, to click on the button using the onclick() event you can use the following solution:
First Element(css_selector):
driver.find_element_by_css_selector("button.btn.btn-primary#YesBtn[onclick*='security_div0']").click()
First Element(xpath):
driver.find_element_by_xpath("//button[#class='btn btn-primary' and #id='YesBtn'][#onclick=\"check_security('security_div0')\"]").click()
Second Element(css_selector):
driver.find_element_by_css_selector("button.btn.btn-primary#YesBtn[onclick*='wlan1security_div0']").click()
Second Element(xpath):
driver.find_element_by_xpath("//button[#class='btn btn-primary' and #id='YesBtn'][#onclick=\"check_security('wlan1security_div0')\"]").click()
First and foremost, you are using a really long xpath which will be difficult to maintain. You can narrow it down further.
Now, some xpaths you can try:
1) Get the second button with the id YesBtn (assuming there are only two buttons with that attribute) :
driver.find_element_by_xpath("(//button[#id= 'YesBtn'])[2]");
2) Find by the onclick attribute:
driver.find_element_by_xpath("//button[#onclick= \'check_security(\'wlan1security_div0\')\']");
button1 with HTML :
<button class="btn btn-primary" style="width: 96px;" type="button" id="YesBtn" onclick="check_security('security_div0')">OK</button>
XPATH :
//button[text()='OK' and #onclick="check_security('security_div0')"]
button2 with HTML :
<button class="btn btn-primary" style="width: 96px;" type="button" id="YesBtn" onclick="check_security('wlan1security_div0')">OK</button>
HTML:
//button[text()='OK' and #onclick="check_security('wlan1security_div0')"]
try:
buttonVar = browser.find_element_by_css_selector(cssSel)
ActionChains(browser).move_to_element(buttonVar).click(buttonVar ).perform()
except Exception as ex:
print("button not found)
Firefox gives you several option you can use with selenium find_element or elements;
by pressing f12 to bring up the inspector,
use the "pick an item" icon in the left corner to select the item you want to view.
This will highlight the text for that item in the inspector, which you can then right click on to bring up a menu where you select "copy" where there are at least 2 find_element options, css_selecor & xpath.
I personally don't like xpath.
They are sometimes long & unruly to work with but whatever suits your style. In my case css_selector works fine.

Unable to click on element with link in selenium python

I am trying to interact with a sign out button but I just can't seem to click on it using link text or xpath.
I have tried following these answers with no luck:
Why Cant I Click an Element in Selenium?
Unable to click link using selenium webdriver in python
Here is my code:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from xatu.tests.base import login
from xatu.tests.bagon import BagonBaseTestCase
class BasicTestCase(BagonBaseTestCase):
#login
def test_logout(self):
self._wait_until_id_presents("quotes-form")
WebDriverWait(self, 10).until(
EC.presence_of_element_located((By.XPATH, "//a[#href='/login/clear']/i")))
self.browser.find_element_by_xpath("//a[#href='/login/clear']/i").click()
self.implicitly_wait(2)
self._title_check("Login")
The first line under test_logout calls a function that waits for a certain element to appear on the webpage so I can see that the page has been loaded. Then I try to click the sign out button.
This is the HTML(element is at class="btn" href="/login/clear"):
<div class="navbar navbar-fixed-top screen-only">
<div class="navbar-inner">
<div class="container-fluid">
<a class="btn btn-navbar" data-target=".nav-collapse" data-toggle="collapse">
<a class="brand" href="/">
<div class="nav-collapse collapse">
<ul class="nav">
<p class="pull-right" style="margin-top: 4px; margin-left: 4px;">
<a class="btn" href="/login/clear">
<i class="icon-off"/>
Sign out
</a>
</p>
<p class="navbar-text pull-right"> Logged-in as D. V. Lauper </p>
</div>
<!--/.nav-collapse -->
</div>
</div>
</div>
When I try finding by link_text, the element can't be found. Running this code gives me a stacktrace error saying:
ElementNotVisibleException: Message: Element is not currently visible and so may not be interacted with
Edit: I've tried Saifur's answer and updated my code to his answer but now I get: AttributeError: 'BasicTestCase' object has no attribute 'find_element'. I've tried changing "self" to "self.browser" as an argument in WebDriverWait() but I would then get my original error.
Use explicit wait and relativexpath
like //a[#href='/login/clear']/i
from xatu.tests.base import login
from xatu.tests.bagon import BagonBaseTestCase
class BasicTestCase(BagonBaseTestCase):
#login
def test_logout(self):
self._wait_until_id_presents("quotes-form")
WebDriverWait(self, 10).until(
EC.presence_of_element_located((By.XPATH, "//a[#href='/login/clear']/i")))
self.browser.find_element_by_xpath("//a[#href='/login/clear']/i").click()
self.browser.implicitly_wait(2)
self._title_check("Login")
You need an explicit wait. See docs. Example code:
element = WebDriverWait(driver, 30).until(EC.visibility_of_element_located((By.XPATH,'//a[#href="/login/clear"]')))
And then just click the element.
element.click()
Note I added my answer b/c -- in my tests at least -- you don't need to worry about the italics tag. That's for the text, not the button -- and you're not clicking the text. So find By.XPATH and select a unique attribute (i.e., the href in this case and very likley not the class attr), and then click your element.
EDIT:
please try this line:
element = WebDriverWait(self.browser, 30).until(EC.visibility_of_element_located((By.XPATH,'//a[#class="btn" and #href="/login/clear"]')))

Categories