How can I click on this check box using Selenium Python? - python

I can click all of the other checkboxes on the page. But when it comes to this one, it won't allow me to click on it
The HTML code for the checkbox is:
<input id="ContentPlaceHolder1_wucSignInStep2_chkTC" type="checkbox" name="ctl00$ContentPlaceHolder1$wucSignInStep2$chkTC">
My code for clicking the text box:
element = driver.find_element_by_xpath('//span[span/input[#name="checkbox checkbox-primary"]]').click()
I can provide the full code if required.

There is an id associated with your input field! You can use the id to find the element
element = driver.find_element_by_id('ContentPlaceHolder1_wucSignInStep2_chkTC').click()
That should do it.
If you are getting an element not visible error then you can try the following:
from selenium.webdriver.common.action_chains import ActionChains
element = driver.find_element_by_id("ContentPlaceHolder1_wucSignInStep2_chkTC")
actions = ActionChains(driver)
actions.move_to_element(element).perform()
driver.execute_script("arguments[0].click();", element)
The above code will make the element visible and also, put the mouse cursor over the checkbox.

Related

Selenium Finding hover button element by class name in python

Happy Sunday,
Trying to click a filter button (called offer) on a website. It is a hover button that does not have an associated link so cannot find element by link text.
When clicking Offer button, the wanted button goes from class="item-list-header-filter-icon item-list-wanted-filter hover-state" to class="item-list-header-filter-icon item-list-wanted-filter hover-state inactive"
I have tried:
driver.find_element_by_class_name(item-list-header-filter-icon item-list-wanted-filter hover-state)
and since it is a dynamic, I made webdriver wait:
try:
element = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.CLASS_NAME, "item-list-header-filter-icon item-list-wanted-filter hover-state inactive"))
)
element.click()
Any ideas much appreciated!
Have a good day
You need to perform a hover over that element.
It can be done as following:
from selenium.webdriver.common.action_chains import ActionChains
offer = driver.find_element_by_css_selector('.item-list-header-filter-icon.item-list-offer-filter')
hover = ActionChains(driver).move_to_element(offer)
hover.perform()
In case all you asked for is to locate that element you can simply do it with
offer = driver.find_element_by_css_selector('.item-list-header-filter-icon.item-list-offer-filter')

Selenium Python Can't click button: ElementNotInteractable or StaleElementReferenceException

I'm trying to automate MS Teams and can't get past the login because after entering the password I am having issues clicking the Sign In button.
If I try:
button = driver.find_element_by_xpath('//*[#id="idSIButton9"]')
button.click()
I get:
ElementNotInteractableException: Message: element not interactable.
If I try to solve it with Action Chains method (which seems to have solved many similiar issues for lots of people):
button = driver.find_element_by_xpath('//*[#id="idSIButton9"]')
driver.implicitly_wait(10)
ActionChains(driver).move_to_element(button).click(button).perform()
I get:
StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
It is worth mentioning that when logging in manually I can get past this stage with pressing return after entering my password but I couldn't be successful with send keys methods neither.
If you still filled the form use submit() function - It is there to make your life easier.
Import webdriver:
from selenium import webdriver
Create webdriver object:
driver = webdriver.Firefox()
Get the website:
driver.get("https://www.YOUR_WEBSITE.de/")
Get element - In your case input for password
element = driver.find_element_by_xpath('//*[#id="i0118"]')
Send keys - Enter password
element.send_keys("YOUR_PASSWORD")
Submit contents
element.submit()
The element which you are trying to locate using the XPath driver.find_element_by_xpath('//*[#id="idSIButton9"]') might be the part of the previous screen and new screen, hence the driver might be referring to the element which is part of the previous screen, hence you are getting the StaleElementReferenceException.
The simplest way to resolve this is you can add, driver.refresh() just before the above xpath, this will load the page and DOM with the new elements.
Else, you can use a different locator strategy which will uniquely identify that element.

Selenium + Python Click on Search Selects but Does Not Click

I have all of my options selected on this form and have the following code to click the Search button:
WebDriverWait(wd, 10).until(EC.element_to_be_clickable((By.ID, "alMatchFrequencies"))).click()
I have also tried this:
search = WebDriverWait(wd, 10).until(EC.element_to_be_clickable((By.ID, "alMatchFrequencies")))
search.send_keys(Keys.ENTER)
I have also tried subbing in RETURN instead of ENTER.
Here is a screenshot after that line is run:
The search bar is highlighted, but no results are being displayed. I can replicate this screen on my own and am able to press the search button so I don't think it is missing fields.
I believe you are actually clicking the search button but are not seeing the results because they are below the view you show. The scrollable area in your screenshot was a clue.
Clicking the search button is as easy as search.click() after you've executed the selector. But then you need to wait and scroll the page.
To Scroll a page you need to introduceActionChains in the Selenium library and to wait for the load you'll need to use Python's time.sleep(sec) function.
Full code to produce the attached picture:
#Imports
import time
from selenium.webdriver.common.action_chains import ActionChains
#...Code to Load and Select Filters...#
search = WebDriverWait(wd, 3000).until(EC.element_to_be_clickable((By.ID, "alMatchFrequencies")))
search.click()
# Wait for element to load
time.sleep(3)
# Locate element to scroll to
results = WebDriverWait(wd,3000).until(EC.presence_of_element_located((By.XPATH, "/html/body/div[1]/section/div/div[2]/div/div[2]/div[5]/div/div[1]/div[5]")))
actions = ActionChains(wd)
# Scroll
actions.move_to_element(results).perform()
wd.get_screenshot_as_file("test3.png")

selenium.common.exceptions.ElementClickInterceptedException: Message: element click intercepted: Element is not clickable with Selenium and Python

I am currently working on a project which fills a form automatically. And the next button appears when the form is filled, that's why it gives me an error.
I have tried:
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH,"//input[#type='button' and #class='button']")))
Next = driver.find_element_by_xpath("//input[#type='button' and #class='button']")
Next.click()
HTML:
<span class="btn">
<input type="button" value="Next" class="button" payoneer="Button" data-controltovalidate="PersonalDetails" data-onfieldsvalidation="ToggleNextButton" data-onclick="UpdateServerWithCurrentSection();" id="PersonalDetailsButton">
</input>
<div class="clearfix"></div>
</span>
ERROR:
selenium.common.exceptions.ElementClickInterceptedException: Message:
element click intercepted: Element is not clickable at point (203, 530).
Other element would receive the click: ... (Session info: chrome=76.0.3809.132)
If the path of the xpath is right, maybe you can try this method to solve this problem. Replace the old code with the following code:
button = driver.find_element_by_xpath("xpath")
driver.execute_script("arguments[0].click();", button)
I solved this problem before, but to be honestly, I don't know the reason.
This error message...
selenium.common.exceptions.ElementClickInterceptedException: Message: element click intercepted: Element is not clickable at point (203, 530). Other element would receive the click: ... (Session info: chrome=76.0.3809.132)
...implies that the click() on the desired element was intercepted by some other element and the desired element wasn't clickable.
There are a couple of things which you need to consider as follows:
While using Selenium for automation using time.sleep(secs) without any specific condition to achieve defeats the purpose of automation and should be avoided at any cost. As per the documentation:
time.sleep(secs) suspends the execution of the current thread for the given number of seconds. The argument may be a floating point number to indicate a more precise sleep time. The actual suspension time may be less than that requested because any caught signal will terminate the sleep() following execution of that signal’s catching routine. Also, the suspension time may be longer than requested by an arbitrary amount because of the scheduling of other activity in the system.
You can find a detailed discussion in How to sleep webdriver in python for milliseconds
As WebDriverWait returns the WebElement you can invoke the click() method directly.
Solution
To click on the button with value as Next you can use either of the following Locator Strategies:
Using CSS_SELECTOR:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input.button#PersonalDetailsButton[data-controltovalidate='PersonalDetails']"))).click()
Using XPATH:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[#class='button' and #id='PersonalDetailsButton'][#data-controltovalidate='PersonalDetails']"))).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
i faced similar issues, the .click() always returns a Not clickable exception. the
driver.execute_script('arguments[0].click()', button)
does the magic. You can also use it to execute any other js script this way
script = 'your JavaScript goes here'
element = driver.find_element_by_*('your element identifier goes here')
driver.execute_script(script, element)
I looked at the exact element that was causing it and it was a banner about consent/cookies. So at first, I made sure it clicked "OK" on the consent banner and then I clicked the other button that I needed. Hope it helps someone.
It look's like there are some other elements which are having the same xpath try changing the xpath something like this
Next = driver.find_element_by_xpath("//input[#id='PersonalDetailsButton']");
Next.Click();
or
Next = driver.find_element_by_xpath(//input[#value='Next' and #id='PersonalDetailsButton']);
Next.Click();
Try first xpath if that doesn't work go with the second one . If that also doesn't work try using sikuli. I am pretty sure that first xpath will work
I faced a similar issue and I observed something that might help to understand the root cause of the issue. In my case, I was able to click at an element being in PC view mode of the website but failed to do so in mobile view (in which I needed my script to run). I found out that in mobile view, ordering of elements (li in my case) changed in view while they remained same in the html document. That's why I was not able to click on it without actually scrolling to it first. It might also explain why this works: -
driver.execute_script("arguments[0].click();", button)
I don't have enough rep to comment but the common reason for this error might be Selenium locates the element from DOM on screen and locate the x-y coordinates (300, 650) then clicks on them but if some changes takes place on screen in between the click duration, for example google ads or some pop-up then it's unable to click on it resulting in this exception
I'm just guessing if anyone has a proper explanation to pls share
I had the same problem too. But my problem was not with the element. The button was activated with href. I changed the code from
<a class="services-button" href="desired url">
To
<a class="services-button" onclick="location.href='{% url "desired url" %}'";">
This solution worked for me :
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
driver = webdriver.Firefox(executable_path="")
driver.get("https://UrlToOpen")
action = ActionChains(driver)
firstLevelMenu = driver.find_element_by_id("menu")
firstLevelMenu.click()
source : http://allselenium.info/mouse-over-actions-using-python-selenium-webdriver/
"selenium.common.exceptions.ElementClickInterceptedException: Message: element click intercepted: Element is not clickable ... "
This exception occurs when element is not found on a web page (When the element we are looking for is at bottom part of the page which is not loaded yet)
So we you can scroll the page using javascript and load complete page and
from selenium.webdriver.common.by import By
from selenium import webdriver
url = "YOUR URL"
SCROLL_PAUSE_TIME = 0.5
driver = webdriver.Chrome()
driver.maximize_window()
driver.get(url)
def scroll_page():
i = 0
while i < 5:
# Scroll down to 500 pixel
driver.execute_script("window.scrollBy(0, 500)", "")
# Wait to load page
time.sleep(SCROLL_PAUSE_TIME)
# Will scroll only for 4 increments of 500px
i += 1
You could try:
driver.execute_script("arguments[0].click();", button)
This solution solved my problems when I faced similar issues.

Not able to get the element in the 2nd iteration [duplicate]

I am trying to select a drop down menu and choose an option. I am using the latest version of Selenium, the latest version of Firefox, the latest version of geckodriver, and the latest version of Python.
Here is my issue: When I try to choose an option, it gives me the following error:
selenium.common.exceptions.ElementNotInteractableException: Message: Element <option> could not be scrolled into view.
I have tried various ways to circumnavigate this issue, but none seem to work. Here are some of the approaches I tried.
mySelectElement = browser.find_element_by_id('providerTypeDropDown')
dropDownMenu = Select(mySelectElement)
dropDownMenu.select_by_visible_text('Professional')
mySelectElement = browser.find_element_by_id('providerTypeDropDown')
dropDown = Select(mySelectElement)
for option in dropDown.options:
message = option.get_attribute('innerText')
print(message)
if message == 'Professional':
print("Exists")
dropDown.select_by_visible_text(message)
break
element = browser.find_element_by_id('providerTypeDropDown')
browser.execute_script("var select = arguments[0]; for(var i = 0; i < select.options.length; i++){ if(select.options[i].text == arguments[1]){ select.options[i].selected = true; } }", element, "Professional")
The HTML code follows the usual select tags and option tags. Any help is appreciated. The HTML code is included below.
<select data-av-chosen="providerTypes" id="providerTypeDropDown" data-placeholder="Please Select a Provider Type" name="providerTypeDropDown"
class="chzn-select input-full ng-pristine chzn-done ng-invalid ng-invalid-provider-type" data-ng-options="providerType.value for providerType in request.models.providerTypes"
data-ng-model="request.models.providerType" data-av-validator-field="providerType" data-disable-search-threshold="5" style="display; none;">
<option value="" class="">Please Select a Provider Type</option>
<option value="0">Professional</option>
<option value="1">Institutional</option>
</select>
The print statements are there for testing/code tracing purposed.
This error message...
selenium.common.exceptions.ElementNotInteractableException: Message: Element <option> could not be scrolled into view.
...implies that the <option> item which your program was trying to interact with could not be scrolled into view.
The HTML of the desired element would have given us some idea behind the error. However it seems the desired element was not clickable / within the Viewport. To address the issue you have to induce WebDriverWait for the element to be clickable and you can use the following solution:
mySelectElement = browser.find_element_by_id('providerTypeDropDown')
dropDownMenu = Select(mySelectElement)
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//select[#id='providerTypeDropDown']//options[contains(.,'Professional')]")))
dropDownMenu.select_by_visible_text('Professional')
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
from selenium.webdriver.support.select import Select
Try to add a wait:
mySelectElement = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, "providerTypeDropDown")))
mySelectElement.click()
it will wait at least 10 seconds until element will be clickable and then click.
Also I don't see in your code, that you click on the dropdown button, which opens dropdown menu. Locate this button, also add a wait and click on it before you select the option. Hope it helps.
Note: for this code you have to add some imports:
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
I had the same problem. Where I was unable to select a dropdown value with selectByValue, selectByIndex and selectByVisible text. I tried actions class and scrollBy using Javascript executor also. Nothing worked. After 1 day of trial and error, I came up with the below workaround,
public static void selectDropDownByVisibleText(WebElement element, String text){
waitForPageLoad();
String firstCharacterDropDownVal = ""+text.charAt(0);
HashSet<String> uniqueDropDownVals = new HashSet<>();
try {
Select select = new Select(element);
select.selectByVisibleText(text);
}catch (ElementNotInteractableException e){
Select select = new Select(element);
while(!select.getFirstSelectedOption().getText().equalsIgnoreCase(text) &&
uniqueDropDownVals.add(select.getFirstSelectedOption().getText())) {
element.sendKeys(firstCharacterDropDownVal);
}
}
log.info("Selected dropdown by visible text "+text);
}
public static void waitForPageLoad() {
log.debug("Waiting for page to get loaded..");
new WebDriverWait(Driver.getDriver(), Duration.ofSeconds(FIND_ELEMENT_WAIT_TIME)).
ignoring(NoSuchElementException.class).ignoring(StaleElementReferenceException.class).
until(webDriver -> ((JavascriptExecutor) webDriver).executeScript("return document.readyState").equals("complete"));
log.debug("Page loaded successfully");
}
I will explain the working. First it will try to select by visible text. If we get the exception it will enter inside the catch block. There we are sending the first character of the desired text on the dropdown webelement. So the dropdown element changes. Let's say the dropdown values are Apple,Aeroplane,Adam and I want to select Adam. First time I send 'A' on the webelement the dropdown changes to Apple. Then I add it to the HashSet and check whether the selected element is the desired element. if it matches then we break out of the while loop. If the same element is added twice, then the HashSet add method will return false. This will break us out of the while loop and keep us from entering into an infinite loop. So each time I enter 'A' the dropdown value changes to the next value that starts with 'A'. This is the approach.

Categories

Resources