DavidK
DavidK

Reputation: 2564

Python - Selenium : Submit form without opening new tab or new window

I have :

driver = webdriver.Firefox()

I have some url : driver.get(url)

I have one form I want to submit :

elt = driver.find_element_by_class_name('special_class')
driver.find_element_by_xpath('//button').click()

This opens a new window and I want everything to happen in one window.

I may have to submit similar things many times and then parse the output.

Is there a way to stay in the same window ? I don't want to have many windows opened.

Thanks in advance.

Upvotes: 3

Views: 3579

Answers (2)

punyidea
punyidea

Reputation: 173

This actually depends on how the form is submitted. If in the HTML the code has <form...id = someID... target = "_blank", and the form element has some identifier you can manually change this attribute.

This opens the form in a new window the next time it is submitted:

Browser.execute_script(
    'document.getElementById("someID").setAttribute("target", "_blank")'
)

If, as you asked, you need to have the form not open in a new window, simply change _blank to _self. (And, of course, someID is a placeholder for the actual form's ID)

Browser is the Selenium WebDriver, and this executes the javaScript code inside, which changes the form's attributes to the desired ones. If the form does not have a unique ID, it's possible that it has another identifying property.

Hope this helped! I found this out myself today.

Upvotes: 3

Petr Mensik
Petr Mensik

Reputation: 27496

I am afraid there is nothing you can do if the button is opening new window after form submission. Only thing which comes to my mind is to use headless browser like PhantomJS - since you are doing web crawling you could appreciate the speed too. See this tutorial for Python.

But I actually remembered there is a workaround for this, you can set Firefox browser.link.open_newwindow to 1, this should cause every new window to be opened in current one. However I am not sure if this will work well with HTML form.

fp = webdriver.FirefoxProfile()
fp.set_preference("browser.link.open_newwindow", 1)
browser = webdriver.Firefox(firefox_profile=fp)

See reference for this feature here.

Upvotes: 4

Related Questions