So recently I have been using Selenium and Python to automate searches/go to websites. And so I looked up how to open new tabs in selenium because opening new windows every time for a search is a pain. I ended up using this code from a solution I found online
browser.execute_script("window.open('');")
time.sleep(2)
browser.switch_to.window(browser.window_handles[1])
browser.get("http://google.com")
to open a new tab. However the problem now arose that I need to close the tabs eventually. I tried using browser.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 'w') to try to close the tab but that didn't work. I also tried to use browser.close() but that just closed the entire window and the rest of the code failed. Any ideas on how to close tabs?
Here is the full code
browser=webdriver.Chrome(chrome_options=options)
browser.get("https://accounts.google.com/ServiceLogin/identifier?service=mail&passive=true&rm=false&continue=https%3A%2F%2Fmail.google.com%2Fmail%2F&ss=1&scc=1<mpl=default<mplcache=2&emr=1&osid=1&flowName=GlifWebSignIn&flowEntry=AddSession")
browser.execute_script("window.open('');")
time.sleep(2)
browser.switch_to.window(browser.window_handles[1])
browser.get("http://google.com")
searchh = browser.find_element_by_name('q')
text = "does CNN do newsletters?"
time.sleep(31)
browser.quit()
In your code you use driver.quit() instead of driver.close()
Difference between webdriver.Dispose(), .Close() and .Quit()
Related
i am having this issue where every time i do
driver.execute_script("arguments[0].click();", element)
or
driver.execute_script("window.open('_blank');")
browser blocks popup and prevents new tab from opening but when i use this
element.click()
It opens new tab without any issue so the problem is i am using webdriver.Remote for multilogin platform to automate some tasks so the execute_script method is very quick on the other hand element.click() takes forever.
What is the difference between them and for execute script new tab won't open i have tried doing this
options = webdriver.ChromeOptions()
options.set_capability("profile.default_content_settings.popups", 0)
driver = webdriver.Remote(link, options=options)
also added the same in experimental options as well as prefs but nothing works
thanks for your time any input is appreciated
I'm opening Firefox browser through selenium(3.141.0) on python 3.9, and it will always start minimized, even though in code I passed function .maximise_window() after opening the browser. When its started this way, it wont execute code to maximise and it wont execute code to switch tabs, and it wont even do it if im trying to switch tabs manually with my mouse.
If I immediately click on the initiated firefox browser on my taskbar when the program is started, it will function normally, but it will open my browsers home tab, and execute my code in new tab. Thats why you may see in code a part that closes that first tab. When i dont do it and when it starts "faulty", the home tab wont be opened.
Im also using the lenght of tabs as an indicator if the browser initiated faulty, where I tried to put it into loop and make it restart till it opens with 2 tabs, but it just wont unless I manually click it.
The only solution so far I can think of is kinda "hacky"...using pyautogui to scan my taskbar after initializing browser and clicking it fast, but I dont really like the idea.
The code goes through my company data warehouse site and manipulates it to download data.
Update
Other hacky solution I found is starting 2 browsers. First won't work, but second will. Meaning that browser works normally IF there is another Firefox browser open at the time.
Snippets of code:
from selenium import webdriver
import time
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
class DWH_browser:
def __init__(self):
self.browser = webdriver.Firefox()
self.browser.maximize_window()
self.browser.get("www.letskeepthecompanysiteasecret.org")
self.len_windows = len(self.browser.window_handles)
print(len(self.browser.window_handles))#this next part is used to close the extra tab when browser
#started normally and opens an extra tab
if len(self.browser.window_handles) == 2:
self.browser.switch_to.window(self.browser.window_handles[0])
self.browser.close()
self.browser.switch_to.window(self.browser.window_handles[0])
self.a = ActionChains(self.browser)
time.sleep(5)
DWH = DWH_browser()#and i initiate it in the code "normally"
#This was the other code I tried using to initate the browser and restart till its in 2 tabs, but not working
# issue_lenght = 1
# while issue_lenght == 1:
# DWH = DWH_browser()
# issue_lenght = DWH.len_windows
# if DWH.len_windows == 1:
# DWH.browser.quit()
# print("RESTARTING BROWSER")
Summarizing your issues:
Always start minimized.
Passed function maximise_window() after opening the browser.
Won't execute code to switch tabs.
To get rid of all these issues you need to ensure that:
Selenium is upgraded to current levels Version 4.4.0.
GeckoDriver is updated to current GeckoDriver v0.31.0 level.
Firefox Browser is updated to current firefox=103.0.2.
Additionally, you won't be needing self.browser.maximize_window() as firefox by default opens in a maximized mode.
Finally, trying to switch tabs manually with my mouse is a big no as the program execution may get interupted.
Hi I am trying to play YouTube using selenium and python. its easy to get played, but i got trouble to close driver after video finish playing. I have tried my script to get text but not really working.
while True:
try:
element = WebDriverWait(driver, 6).until(
EC.presence_of_element_located((By.XPATH, "//*[contains(text(),'My Video title')]"))
)
except:
break
driver.close()
driver.quit()
code above is to close after video title is change, but only working when i refresh the page. May be somebody can help with this code or may have another elegant method to do the job
You could force it to quit using the exit function of the os library os.exit(0)
(for alternatives to os.exit(0) see geeks for geeks python exit commands), but that would terminate the entire program which I am not quite sure that you want to do.
I have a Python program that uses APScheduler and Selenium to automate webscraping. Basically it scrapes a particular website once every hour, and then schedules certain more detailed scrapes to happen at intervals.
The issue is that while I want to start the scraper, and then be free to use my computer for other work, Selenium will then automatically focus on the opened chrome tabs whenever a new scrape is started by APScheduler. Because of this, I am trying to find a way to have the new chrome windows open - but I don't have to focus on them. I've already tried headless and phantomJS, but the site is dynamically generated so these don't really work.
My current solution is to open the new window, minimise it, and then immediately shift back to the old window. To do this I want to perform a keyboard shortcut using ActionChains. I currently have this test code:
driver = webdriver.Chrome(ChromeDriverManager().install())
ActionChains(driver).key_down(Keys.CONTROL)
ActionChains(driver).send_keys(Keys.RIGHT)
ActionChains(driver).key_up(Keys.CONTROL)
Currently this code does nothing however. Is there anyway to fix this? I am using Jupyter Notebook and I am on a mac for reference.
NOTE: this code is being run apart from the main program, I am just using it to test if the script will work.
Try this out. You never .perform() it.
ActionChains(driver).key_down(Keys.CONTROL).send_keys(Keys.RIGHT).key_up(Keys.CONTROL).perform()
I have a two like like below
<body>
contact
Sest
</body>
After click on link page has open in new tab , I want to close this tab without close driver, Is it possible ? I have tried below code but not working.
link = driver.find_element_by_xpath(
"//a[contains(text(),'contact') or contains(text(),'est')]")
link.click()
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 'w')
You can switch between windows by using driver.window_handles to identify all the windows currently open in your driver's browser. Then you can move between them using `driver.switch_to_window(). Here's an example:
tabs = driver.window_handles #get list of open windows
driver.switch_to_window(tabs[1])
driver.close() #close the current window
driver.switch_to_window(tabs[0]) #return to first window
A tab is nothing more than another window (from the eyes of selenium)
To close a window you must switch to it, then call driver.close(). This does NOT cause selenium to quit the driver itself, which I suspect is what you might be afraid of.
To switch to a window, you'll need the window ID.
driver.current_window_handle gives you the window you're currently focused. driver.window_handles will give you a list of all the windows open. Assuming you only have two windows open, it should be easy to identify the one you want to close.
Lastly, don't forget to switch back to the original window. Closing a window does not automatically move your focus back to a window.
driver.switch_to.window(window_id)
driver.close()
driver.switch_to.window(original_id)
It's like a real browser. If you close the one and only tab, the browser closes himself. Try not to open the second Tab in a new Tab, just use the other you don't want anymore.