0

login.php calls the following function when submitted

<script type="text/javascript">
  function validate(){
    var res=confirm("Are you sure");
    if(res)
      return true;
    else
      return false;
  }
</script>

I am trying to login through a python script using Selenium. When I click login the following script is called and I need to select 'yes' to login.

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

browser = webdriver.Firefox()
browser.get("webpage/login.php")

username = browser.find_element_by_id("id")
password = browser.find_element_by_id("pass")
username.send_keys("username")
password.send_keys("password")
login_attempt = browser.find_element_by_xpath("//*[@type='submit']")
login_attempt.submit()

#I want to send yes to the `validate` function and the
#then then again do browser.get("webpage/home.php") to scrape info from a html tag

#print(login_attempt.submit())

I am relatively new to what I am trying to do .. suggestions are well received if there are better practices.

rainversion_3
  • 887
  • 1
  • 14
  • 30
  • Please try already posted answer 'https://stackoverflow.com/questions/46105357/how-to-handle-new-poped-up-browser-window-with-java-selenium/46109119#46109119' – Pankaj Sharma Sep 12 '17 at 18:13
  • [this](https://stackoverflow.com/a/29052586/3989888) turned out to be useful but `xpath(u'//input[@value="OK"]').click()` part is not working .. so what is the element type of `Ok` button on `window.confirm` – rainversion_3 Sep 12 '17 at 20:49

2 Answers2

1

The pop up come out after click submit, we call them JS alert/confirm, they trigger by JavaScript and supported natively by browser. For such pop-up, selenium had already implement the code to interact with them. So just to find the methond from selenium python client API on the version you used. (The methond name and how to call maybe not same in different client API version).

alert = browser.switch_to_alert()
//accept the alert
alert.accept()

// maybe as below to call
alert = driver.switch_to.alert
alert.accept()

// or
Alert(driver).accept()
yong
  • 13,357
  • 1
  • 16
  • 27
  • `selenium.common.exceptions.WebDriverException: Message: Failed to convert script to String` – rainversion_3 Sep 12 '17 at 17:30
  • please see this post: https://seleniumwithjavapython.wordpress.com/selenium-with-python/handling-javascript-alerts/ – yong Sep 13 '17 at 00:17
  • http://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.common.alert – yong Sep 13 '17 at 00:29
  • `alert.accept()` is working but in my case it was taking some time to detect ... I had time.sleep(2) and it worked like normal – rainversion_3 Sep 16 '17 at 16:55
0

Use following code:

browser = webdriver.Firefox()
browser.get("http://username:password@webpage/login.php")

you will be able to bypass this authentication alert.