How to close iframe selenium python - python-3.x

1 click button in website it shown iframe like popup and I can edit it but I cant close iframe I try to use X button but when mouse focus in button it change the class name and shown text on mouse , it don't have id.
this is source of button
<a class="jbox-close" title="Close" onmouseover="$(this).addClass('jbox-close-hover');" onmouseout="$(this).removeClass('jbox-close-hover');" style="position:absolute; display:block; cursor:pointer; top:11px; right:11px; width:15px; height:15px;"></a>
this is code focus mouse
<a class="jbox-close jbox-close-hover" title="Close" onmouseover="$(this).addClass('jbox-close-hover');" onmouseout="$(this).removeClass('jbox-close-hover');" style="position:absolute; display:block; cursor:pointer; top:11px; right:11px; width:15px; height:15px;"></a>
this is my code
for link in tittle:
a = link.get_attribute('title')
if (a == "Packaging Details"):
link.click()
time.sleep(2)
print(driver.current_url)
iframe=driver.find_element_by_tag_name('iframe')
driver.switch_to.frame(iframe)
time.sleep(2)
print(driver.find_element_by_id("width").get_attribute('value'))
print(type(driver.find_element_by_id("width").get_attribute('value')))
print(widthctn)
driver.find_element_by_id("width").send_keys("",widthctn)
time.sleep(1)
driver.find_element_by_name("btnSave").click()
time.sleep(1)
driver.switch_to.window(driver.window_handles[1])
``
and this error
raceback (most recent call last):
File "C:/Users/dtung/PycharmProjects/BS4/multiple tab.py", line 79, in
link.click()
File "C:\Users\dtung\miniconda3\envs\BS4\lib\site-packages\selenium\webdriver\remote\webelement.py", line 80, in click
self._execute(Command.CLICK_ELEMENT)
File "C:\Users\dtung\miniconda3\envs\BS4\lib\site-packages\selenium\webdriver\remote\webelement.py", line 633, in _execute
return self._parent.execute(command, params)
File "C:\Users\dtung\miniconda3\envs\BS4\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "C:\Users\dtung\miniconda3\envs\BS4\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.ElementClickInterceptedException: Message: element click intercepted: Element ... is not clickable at point (257, 505). Other element would receive the click:
(Session info: chrome=81.0.4044.113)

If you are asking about iframes, you can find your answer here Selenium and iframe in html,
But your error looks like some element/alert is hiding your actual element where you want to click. You can achieve click using js executor if element is not visible or hidden by some other element.
eg: assuming click is failed,
btnSave = driver.find_element_by_name("btnSave")
driver.execute_script('arguments[0].click();', btnSave)

You can't close iframe instead of that once you finished processsing elements on a iframe you can switch control back to your parent window using driver.switch_to.default_content()
find more on how to handle iframes

Related

KeyError: 'document' occures when I try to use execute_script command in Python Selenium

I have simple code. Firstly I get an input from user. In target page, there is an editable div. I focus on it and insert the message that I got from user. When I focusing and inserting element I use Javascript so for using Javascript with Python Selenium I use execute_script command.
Code:
message = input()
message = message.replace("'","\\'")
message = message.replace('"','\\"')
browser.execute_script("setTimeout(function() {document.querySelector('._3ee1T ._3uMse ._2FVVk ._3FRCZ').focus();}, 0); document.querySelector('._3ee1T ._3uMse ._2FVVk ._3FRCZ').textContent = '{}'".format(message))
Error: Traceback (most recent call last): File "main.py", line 171, in <module> browser.execute_script("setTimeout(function() {document.querySelector('._3ee1T ._3uMse ._2FVVk ._3FRCZ').focus();}, 0); document.querySelector('._3ee1T ._3uMse ._2FVVk ._3FRCZ').textContent = '{}'".format(message)) KeyError: 'document'

Selenium python can't send keys to second input field

I'm trying to fill in a webform with selenium and python.
I'm looping trough all input fields and sending each a "Test" string.
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome('C:/Users/kbu/chromedriver.exe')
driver.get('https://skovbakken.halbooking.dk/proc_error.asp')
all_inputs = driver.find_elements_by_xpath("//input[#class='textbox_login']")
for input in all_inputs:
input.send_keys("Test")
Only the first is filled out. Why is that?
This is the error i get:
Traceback (most recent call last):
File "C:\Users\kbu\Dropbox\Python\squash.py", line 10, in <module>
input.send_keys("Test")
File "C:\Users\kbu\AppData\Local\Programs\Python\Python38\lib\site-packages\selenium\webdriver\remote\webelement.py", line 477, in send_keys
self._execute(Command.SEND_KEYS_TO_ELEMENT,
File "C:\Users\kbu\AppData\Local\Programs\Python\Python38\lib\site-packages\selenium\webdriver\remote\webelement.py", line 633, in _execute
return self._parent.execute(command, params)
File "C:\Users\kbu\AppData\Local\Programs\Python\Python38\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "C:\Users\kbu\AppData\Local\Programs\Python\Python38\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.ElementNotInteractableException: Message: element not interactable
(Session info: chrome=84.0.4147.125)
Here is the HTML:
The Locator Strategy which you have used:
driver.find_elements_by_xpath("//input[#class='textbox_login']")
identifies exactly 3 elements within the HTML.
The first and last elements are the username and password field respectively.
But the second matching element contains the style attribute value as style="DISPLAY: none;:
<input onkeydown="CheckEnterNoIE('logon', event.keyCode)" name="mf_nnpg0fjm" type="password" id="mf_nnpg0fjm" onfocus="if(this.value==multiform.loginvar6.value){this.value='';}" maxlength="50" tabindex="1" class="textbox_login" style="DISPLAY: none;width:120px;">
Hence when your script tries to invoke send_keys() on it you face ElementNotInteractableException.
Reference
You can find a couple of relevant discussion on ElementNotInteractableException in:
Element not Interactable when using the selenium function find element by name but works when using find element by xpath method
ElementNotInteractableException: Message: element not interactable error sending text in search field using Selenium Python

How to Handle Popup Windows That Occur within Selenium Python

So I have an issue where, I am trying to automate an Import on an application that has no API.
As a result, I have to do like 30 navigation clicks just to get to what I want (Exaggeration).
However, I am trying to basically automate the clicks that will allow me to upload a specific file.
As a result, I almost get to the part where I have to select the specific test build I want to import the file with. There is a field that I need to do a send_keys to find the correct import build I have to upload. The Field element looks like this
<input class="lookupInput" type="text" name="brTestScoreImportLookupInput" id="brTestScoreImportLookupInput" style="width: 100px;" tabindex="1" onkeydown="return lookupKeyPressed(event,"","simptbrws000.w")" origvalue="" det="true" aria-labelledby="" autocomplete="off">
However I don't think my code is properly handling the window as it pops-up from the prior selection.
The field I need to update can be found in the picture I uploaded:
Furthermore the XPATH for the Field is //*[#id='brTestScoreImportLookupInput']
You can find the full code here.
The main aspect is I have to Enter TSI into that File ID field and then hit enter on my keyboard to populate the correct import utility I need. Once I do that the import utilities filter out and I need to select a specific File ID:
.
The main code that should be controlling this:
# Click on Test Score Import Wizard - TW
# Test Wizard XPATH = //a[#id='tree1-3-link']/span
element = WebDriverWait(browser, 20).until(
EC.element_to_be_clickable((By.XPATH, "//a[#id='tree1-3-link']/span")))
element.click();
# Send test_upload and Send Keys
# Field XPATH = //*[#id='brTestScoreImportLookupInput']
test_lookup = browser.find_element_by_id("brTestScoreImportLookupInput")
test_lookup.send_keys(test_upload)
If you want to visit the link toe repository code click on here above this.
Any help would be greatly appreciated.
Traceback (most recent call last): File ".\skyward_collegeboard_TSI_import.py", line 115, in
<module> test_lookup = browser.find_element_by_id("brTestScoreImportLookupInput") File "C:\Python38\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 360, in find_element_by_id return self.find_element(by=By.ID, value=id_) File "C:\Python38\lib\site-packages\selenium\webdriver\remote\webdriver.py",
line 976, in find_element return self.execute(Command.FIND_ELEMENT, { File "C:\Python38\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute self.error_handler.check_response(response) File "C:\Python38\lib\site-packages\selenium\webdriver\remote\errorhandler.py",
line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"[id="brTestScoreImportLookupInput"]"}
(Session info: chrome=80.0.3987.122)
So I was able to accomplish this by using the following method using both selenium and pynput.
# Browser Switches to Window
WebDriverWait(browser,10).until(EC.number_of_windows_to_be(2))
browser.switch_to.window(browser.window_handles[-1])
# Send test_upload and oend Keys
# Field XPATH = //*[#id='brTestScoreImportLookupInput']
test_lookup = browser.find_element_by_id("brTestScoreImportLookupInput")
test_lookup.send_keys(test_upload)
# Press and Release Enter Key
keyboard.press(Key.enter)
keyboard.release(Key.enter)
Essentially I had to switch to that popup window.

Selenium: entering Username with find_element_by_name, how to locate Name?

I'm using a bit of code from a related question
username = driver.find_element_by_name("username")
username.send_keys("username")
I looked at the source code for the login page, and saw:
HTML snippet
However, I'm getting errors for both
username = driver.find_element_by_name("Email")
and
username = driver.find_element_by_name("ember442")
The error says:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/anaconda/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 385, in find_element_by_name
return self.find_element(by=By.NAME, value=name)
File "/anaconda/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 791, in find_element
'value': value})['value']
File "/anaconda/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 256, in execute
self.error_handler.check_response(response)
File "/anaconda/lib/python3.6/site-packages/selenium/webdriver/remote/errorhandler.py", line 194, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"name","selector":"Email"}
What am I doing wrong here? My only other thought would be to use one of the other commands for locating elements (find_element_by_id,
find_element_by_name,
find_element_by_xpath,
find_element_by_link_text,
find_element_by_partial_link_text,
find_element_by_tag_name,
find_element_by_class_name,
find_element_by_css_selector) but those don't seem to work either.
It's because none of those are element names. You should use :
username = driver.find_element_by_id("ember442")
Here is the Answer to your Question:
For Email try xpath as //input[#id='ember442']:
username = driver.find_element_by_xpath("//input[#id='ember442']")
username.send_keys("username")
For Password try xpath as //input[#id='ember443']:
username = driver.find_element_by_xpath("//input[#id='ember443']")
username.send_keys("username")
Let me know if this Answers your Question.
Got it! I ended up finding a related question (albeit one using Java) and a piece of code in an answer: driver.findElement(By.xpath("//input[#name='name']")) and modified it to read: username = driver.find_element_by_xpath("//input[#placeholder='Email']"‌​)
I'd love to know how to do this by referencing the id name (find_element_by_id) but this was a task-specific question so it'll work for now!
TLDR; I had to specify the placeholder name within find_element_by_xpath.

Navigating a Website with Selenium Webdriver

My goal is to automate online bill pay using Selenium for Python.
Login was successful using Webdriver with this code:
from selenium import webdriver
browser = webdriver.Firefox()
browser.get('https://website.com/Home')
emailElem = browser.find_element_by_id('UserName') #finds login username field
emailElem.send_keys('username') #enter the username
passwordElem = browser.find_element_by_id('UserPassword') #finds pw field
passwordElem.send_keys('password') #enters pw
passwordElem.submit() #presses submit button
After login, a new page loads, and my next step is to click on a link. The code:
browser.implicitly_wait(3) #allow new page to load (also tried 5 seconds)
click_link = browser.find_element_by_link_text("Bill & Payment")
click_link.click()
And nothing happens. No navigation to the Bill & Payment page. The actual link has a <BR> tag in it, so I also tried including the tag:
click_link = browser.find_element_by_link_text("Bill &<BR>Payment")
But still nothing. What are some other things I should try?
Errors:
Traceback (most recent call last):
File "/home/captain/.PyCharmEdu30/config/scratches/scratch_1.py", line 12, in
click_link = browser.find_element_by_link_text("Bill & Payment")#clicks link on next page
File "/home/captain/.local/lib/python3.5/site-packages/selenium/webdriver/remote/webdriver.py", line 317, in find_element_by_link_text
return self.find_element(by=By.LINK_TEXT, value=link_text)
File "/home/captain/.local/lib/python3.5/site-packages/selenium/webdriver/remote/webdriver.py", line 752, in find_element
'value': value})['value']
File "/home/captain/.local/lib/python3.5/site-packages/selenium/webdriver/remote/webdriver.py", line 236, in execute
self.error_handler.check_response(response)
File "/home/captain/.local/lib/python3.5/site-packages/selenium/webdriver/remote/errorhandler.py", line 192, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: {"method":"link text","selector":"Bill & Payment"}
Stacktrace:
at FirefoxDriver.prototype.findElementInternal_ (file:///tmp/tmps7uj9u0l/extensions/fxdriver#googlecode.com/components/driver-component.js:10770)
at fxdriver.Timer.prototype.setTimeout/<.notify (file:///tmp/tmps7uj9u0l/extensions/fxdriver#googlecode.com/components/driver-component.js:625)
The error that you are experiencing is that the element that you are looking for is not in the page. In my experience with Selenium, I have found that css selectors often work the best for interactive with a website. You can also run python from the command line to test if you have a good hook value for an element by:
from selenium import webdriver
browser = webdriver.Firefox()
browser.get('https://website.com/Home')
element = "what you want to test here"
driver.find_element_by_id(element).click()
And you can just keep changing the value of element and running the lines as long as you keep the python interpreter open.
If the problem seems to be that Selenium doesn't wait long enough for the page to load, you can always try a wait method like:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec
time = 10 # Wait for 10 seconds
by = By.CSS_SELECTOR # The type of hook the element is
hook = "css.selector.here" # The value for the hook (could also be xpath, name, id, etc.)
# Waits until either the element specified by variables by and hook is
# In the page, or the value of time seconds has passed.
WebDriverWait(self.driver, time).until(ec.presence_of_element_located((by, hook)))
driver.find_element(by, hook).click()
Documentation is usually too technical for me to follow, but it was pretty straightforward for Selenium Python Bindings.
Because there was some formatting in the link text, I used the partial link text method and it worked.
example from the documentation:
continue_link = driver.find_element_by_partial_link_text('Conti')
Try to use
click_link=driver.find_element_by_xpath(eg.xpath of 'online bill pay' link)
click_link.click()

Resources