driver.find_element(By.XPATH, "//input[#name = 'SelectAll' and #value='Move All >>>']").click()
driver.find_element(By.NAME, "Submit1").click()
For background, this is part of a script that goes to a website, completes a few actions/prompts, and pulls a CSV file. The code above works most of the time but sometimes gives an error of,
UnexpectedAlertPresentException: unexpected alert open: {Alert text : No contracts have been selected.}
(Session info: headless chrome=97.0.4692.99)
This is from a page where you have to move list items over from one dialogue box to another. You receive this error when nothing has been pulled over. Also as a note, I do have an implicitly_wait(100) before this code.
I am trying to get the above code to run through a loop where it will keep repeating/retrying the code until there is a success.
If I clearly understnd what goes there:
You want to continue performing the 2 click actions you mentioned until no alert appeared.
I.e. in case alert appearing - close the alert and perform the clicks again.
In case no alert appeared - no more need to click these 2 elements, continue further with the next code.
If so you can do something like this:
while True:
driver.find_element(By.XPATH, "//input[#name = 'SelectAll' and #value='Move All >>>']").click()
driver.find_element(By.NAME, "Submit1").click()
try:
alert = driver.switch_to.alert
alert.accept()
except:
break
Related
How should I check if the following is working? What can I do, to get a true or false response?
driver.find_element_by_link_text("XXXX").click()
let's say when you fire a .click event, a event occurs in UI (for an example after clicking on login button, we see dashboard page title or heading)
what we would do in this case is to assert that heading, or title, if assertion works then script will get to know that the previous .click was actually done, cause if it was not then assertion would have failed.
try:
driver.find_element_by_link_text('some text').click()
# put some delay here, WebDriverWait or time.sleep()
assert driver.find_element_by_xpath('dashboard page heading web xpath here').text in "expected dashboard heading"
print('Assertion worked so .click was correct')
except:
print('Assertion must have failed')
Clicking on a link typically takes you to another window/tab. You can capture the title/url of that page and assert that click operation worked
try:
ele=driver.find_element_by_link_text("XXXX")
if (ele):
print "this link exists in the page"
except:
print("there is no such link in the page")
there are multiple windows to get the info
I have a csv with keys to search in the first column, sometimes the website doesn't contain the element so I want driver quit then it can send the next key.
Here I give a specific example key I wanna search (and a normal situation):
url = 'http://biz.finance.sina.com.cn/suggest/lookup_n.php?country=&q=21%BD%F0%BF%C602'
# the following is a normal situation with all elements exist
# url = 'http://money.finance.sina.com.cn/bond/quotes/sz149373.html'
driver.get(url)
try:
driver.switch_to.window(driver.window_handles[-1])
driver.find_element_by_xpath('//div[#class="title tit06"]/a').click()
driver.switch_to.window(driver.window_handles[-1])
driver.find_element_by_link_text('基本资料').click()
driver.switch_to.window(driver.window_handles[-1])
driver.find_element_by_link_text('发行信息').click()
except:
try:
driver.switch_to.window(driver.window_handles[-1])
driver.find_element_by_link_text('基本资料').click()
driver.switch_to.window(driver.window_handles[-1])
driver.find_element_by_link_text('发行信息').click()
except:
#error after quitting, cannot continue to search next key
**driver.quit()**
driver.switch_to.window(driver.window_handles[-1])
driver.find_element_by_link_text('基本资料').click()
driver.switch_to.window(driver.window_handles[-1])
driver.find_element_by_link_text('发行信息').click()
ERROR:MaxRetryError: HTTPConnectionPool(host='127.0.0.1', port=63963): Max retries exceeded with url:
When the chrome quit in the highlighted line, then the error shows as above.
Many thanks!!
driver.quit() will shutdown all of driver operation in your computer. The error you receive mean it able to find your driver because it has been shutdown by your code.
No further interaction can be execute.
If you want to close the current website, in your current window.
Switch back to your parent window and using driver.close() instead (Remember to keep track of your parent window):
driver.switch_to.window(parent_window)
driver.close()
It only close the current window your driver is focusing on.Code example for your case:
for key in read_key_from_csv:
# declare your driver inside loop
driver = webdriver.Chrome()
driver.get(key)
# put all your code in side the loop
# in case it not find element you want close the driver, the loop will jump to next key and start new driver
driver.close()
# no action relate to driver can perform after you close it
acc = self.wait.until(EC.visibility_of_element_located((By.XPATH,"//tr[#valign='top']/td[2]/input[#id='account']")))
acc.send_keys(user['userid'])
time.sleep(1)
pwd = self.wait.until(EC.visibility_of_element_located((By.XPATH, "//tr[#valign='bottom']/td/input[#id='passwordInput1']")))
pwd.send_keys(user['pwd'])
I tried to login to a website and i can successfully input the account name--that is "acc" in the codes, but when it came the pwd, it will display an error message. And i tested that the pwd element can be fine, only the send_keys line went wrong.
selenium.common.exceptions.ElementNotInteractableException: Message: Element <input id="passwordInput1" class="inputField1" name="passwordInput1" type="text"> is not reachable by keyboard
It occurred in geckodriver and chromedrive, but was okay with phantomjs. Anyone knows what's happening?
The keyboard is not available at that time.It mean that using a keyboard is not effective.The situation I've encountered is that the page has changed, and the popup window, for example, alter.You should use :
driver.save_screenshot('screen.png')
try:
pwd = self.wait.until(
EC.visibility_of_element_located((By.XPATH, "//tr[#valign='bottom']/td/input[#id='passwordInput1']")))
pwd.send_keys(user['pwd'])
except Exception as e:
print(e)
driver.save_screenshot('screen.png')
to see the page status at that time.
You could try sending text by action chains:
import selenium.webdriver.common.actions
ActionChains(driver).send_keys_to_element(element, password).perform()
Where:
driver is the driver you are using,
element is your located element,
password is the text you want to send.
This solved my similar issue.
Docs:
https://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.common.action_chains
I want to emulate the following behavior in selenium python (python v2.7, selenium v3.4.2, geckodriver):
Click link on the page which opens pop up window
Select link on pop up window and click it
Do something else on the main window
I have the following code:
main_window_handle = None
while not main_window_handle:
main_window_handle = driver.current_window_handle
driver.find_element_by_xpath('//*[#title="Open Search Window"]').click()
search_window_handle = None
while not search_window_handle:
for handle in driver.window_handles:
if handle != main_window_handle:
search_window_handle = handle
break
driver.switch_to.window(search_window_handle)
driver.switch_to.frame("resultsFrame")
print "Clicking results frame"
driver.find_element_by_link_text("TestResult").click()
print "Expecting window to close"
driver.switch_to.window(main_window_handle)
It works for opening pop up window, selecting frame and clicking link on that frame. Pop up is closed (which is correct) but selenium hangs after that and print statement with "Expecting window to close" never gets executed. It looks very strange especially that selenium never timeouts and keeps hanging until process is manually interrupted.
EDIT:
It looks that it can be a problem with geckodriver, I executed code with chromedriver and it worked.
https://gist.github.com/codyc4321/724f05aca8f6775e2fc1
Hi, bitbucket changed their login page, and is giving me a hassle. Based on the following gist, using driver.click_button causes:
ElementNotVisibleException at /bitbucket/create-repo
Message: Element is not currently visible and so may not be interacted with
Stacktrace:
at fxdriver.preconditions.visible (file:///tmp/tmpSNzLIl/extensions/fxdriver#googlecode.com/components/command-processor.js:9981)
at DelayedCommand.prototype.checkPreconditions_ (file:///tmp/tmpSNzLIl/extensions/fxdriver#googlecode.com/components/command-processor.js:12517)
at DelayedCommand.prototype.executeInternal_/h (file:///tmp/tmpSNzLIl/extensions/fxdriver#googlecode.com/components/command-processor.js:12534)
at DelayedCommand.prototype.executeInternal_ (file:///tmp/tmpSNzLIl/extensions/fxdriver#googlecode.com/components/command-processor.js:12539)
at DelayedCommand.prototype.execute/< (file:///tmp/tmpSNzLIl/extensions/fxdriver#googlecode.com/components/command-processor.js:12481)
using driver.submit_form causes error in the browser itself:
using driver.activate_hidden_element causes:
ElementNotVisibleException at /bitbucket/create-repo
Message: Element is not currently visible and so may not be interacted with
activate_hidden_element failing really took the wind outta my sails for the last 5 minutes. How can I click this stonewalling button? Thank you
Okay, so the problem is actually in your locate_element method.
When you check for the xpath: "//button[normalize-space(text())='{text}']" it finds a button successfully but it is not the login button you are looking for. If you switch that with the input xpath: "//input[#value='{text}']" it finds the right input and successfully logs you in.
You should also remove the last two lines in the BitbucketDriver.login() method because the line self.click_button(search_text="Log in") throws an AttributeError.
Your locate_element method should look like this:
def locate_element(self, search_text, xpaths=None):
if not xpaths:
xpaths = [ "//input[#value='{text}']", "//button[normalize-space(text())='{text}']",
"//a[child::span[normalize-space(text())='{text}']]", "//a[normalize-space(text())='{text}']"]
try:
return self.driver.find_element_by_id(search_text)
except:
try:
return self.driver.find_element_by_name(search_text)
except:
try:
return self.driver.find_element_by_class_name(search_text)
except:
for path in xpaths:
try:
return self.driver.find_element_by_xpath(path.format(text=search_text))
except:
pass
return None