[英]Python - Selenium : Submit form without opening new tab or new window
I have : 我有 :
driver = webdriver.Firefox()
I have some url : driver.get(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. 提前致谢。
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. 我想到的只是使用像PhantomJS这样的无头浏览器 - 因为你正在进行网络爬行,你也可以欣赏速度。 See this tutorial for Python. 请参阅本教程了解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. 但实际上我记得有一个解决方法,你可以将Firefox browser.link.open_newwindow
设置为1
,这应该会导致每个新窗口在当前窗口中打开。 However I am not sure if this will work well with HTML form
. 但是我不确定这是否适用于HTML form
。
fp = webdriver.FirefoxProfile()
fp.set_preference("browser.link.open_newwindow", 1)
browser = webdriver.Firefox(firefox_profile=fp)
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. 如果在HTML中代码具有<form
... id = someID
... target = "_blank"
,并且表单元素具有一些标识符,则可以手动更改此属性。
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
. 如果,当你问,你需要有形式在不打开一个新的窗口,只需更改_blank
到_self
。 (And, of course, someID
is a placeholder for the actual form's ID) (当然, someID
是实际表单ID的占位符)
Browser
is the Selenium WebDriver, and this executes the javaScript code inside, which changes the form's attributes to the desired ones. Browser
是Selenium WebDriver,它在里面执行javaScript代码,它将表单的属性更改为所需的属性。 If the form does not have a unique ID, it's possible that it has another identifying property. 如果表单没有唯一ID,则可能有另一个标识属性。
Hope this helped! 希望这有帮助! I found this out myself today. 我今天发现了这个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.