Selenium script searches previous tab's HTML after opening a new tab - python

After opening a new tab using selenium, I tried to look for an element in the new tab – but the script is still searching on the html script from the previous tab. How do I make it so that after I open a new tab, it searches the open tab's HTML instead of a previous one's?
Below is my code (it doesn't work since I try and search for an element on the new tab, but the script searches for it on the first tab).
options = webdriver.ChromeOptions()
options.add_argument("user-data-dir=C:\\Users\\jack_l\\AppData\\Local\\Google\\Chrome\\User Data")
options.add_argument(r'--profile-directory=Profile 8')
driver = webdriver.Chrome(ChromeDriverManager().install(), options=options)
#Opens the Chrome browser
driver.get("https://www.beatstars.com/")
#Opens a new tab on the browser and goes to that URL
driver.execute_script("window.open('https://www.tunestotube.com/', 'new window')")
#Doesn't work since it's searching for a "tunestotube" element on "beatstars"
theText = driver.find_element(By.XPATH, "/html/body/div[2]/div[2]/div[2]").text
Any help would be greatly appreciated.

driver.execute_script("window.open('https://www.tunestotube.com/', 'new window')")
driver.switch_to.window( driver.window_handles[1])
theText = driver.find_element(By.XPATH, "/html/body/div[2]/div[2]/div[2]").text
When you open a tab you get a handle you need to switch back to the previous handle and then find your element.

Found a solution: You need to switch to the new window
Below is code that gets a website on the first tab, opens a new tab with another website, and then can read/find elements in that new tab.
#Gets a browser and sets the window to a variable
driver.get("https://www.exampleWebsiteForFirstTab.com/")
window_before = driver.window_handles[0]
#Open a new tab and sets the window to a variable
driver.execute_script("window.open('https://www.exampleWebsiteForSecondTab.com/', 'new window')")
window_after = driver.window_handles[1]
#Switches the current window to the new tab
driver.switch_to.window(window_after)
###DO WHATEVER YOU WANT IN THE NEW TAB
#Switches the current window to the old tab
driver.switch_to.window(window_before)
Hopefully this helps anyone who had the same problem I did!

Related

Open multiple URL's from a list in new tabs and get the title of each of them

I am trying to open multiple websites from a list in new tabs and get the title of each page.
It works properly when all the websites are up and running..If incase the website is down, that tab is being replaced by the next url in the list.. I want to have that page open even if the page is not working and next url in the list to be opened in the next tab..
This is the code which i m trying :
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
service = Service(
"C:\\Users\\vbred\\Desktop\\Selenium with python\\Selenium\\chrome\\chromedriver_win32\\chromedriver.exe")
chrome_options = Options()
chrome_options.add_experimental_option("detach", True)
driver = webdriver.Chrome(options=chrome_options)
pages = ['https://www.facebook.com/', 'https://www.commbank.com.au/','https://www.commbank.com'
'https://chercher.tech/python/windows-selenium-python']
for p in range(len(pages)):
try:
driver.get(pages[p])
if p!=len(pages)-1:
driver.execute_script("window.open('');")
windows = driver.window_handles
driver.switch_to.window(windows[-1])
except Exception as e:
print(e)
for p in range(len(pages)):
if p != len(pages):
childwindow = driver.window_handles
driver.switch_to.window(childwindow[p])
print(driver.title)
EXPECTED :
All the 4 urls to be opened in different tabs , even if the the third url is not working..
ACTUAL :
First 2 urls are opened in different tabs, but as the third url is not working , in the third tab 4th url is being opened and i dont see the not working url at all
There should be a comma in your 'pages' list (at the end of the 3rd item). I am not sure if it is a typo or you just miss it in your code.
BTW, I prefer open a new tab before the driver gets urls, which means:
driver.execute_script("window.open('');")
windows = driver.window_handles
driver.switch_to.window(windows[-1])
driver.get(pages[p])
Imaginition:
Open the new blank tab.
Get the windows ID.
Switch to it.
Go to the website by driver.get().
Loop until ends.
Maybe you can have a try. Good luck!

How to open new website via selenium and than open new tab and close new tab and work with first tab in python

i tried to work with selenium web driver for this plan " i open new link via selenium web driver on example website called scene-rls and do some work in this site and after i open new tab to open google.com then do some works and close the google tab and back to scene-rls tab and do new work on the scene-rls tab , but in my code when i open google.com and close the tab and back to the scene-rls tab the code return error like this:
selenium.common.exceptions.NoSuchWindowException: Message: no such window: window was already closed
and my code is :
Regular_part = "Ambulance Australia S02E05 WEB H264-FLX"
driver =
webdriver.Chrome(executable_path=r'C://chromdriver//chromedriver.exe')
x = True
while x:
driver.get('http://scene-rls.net/?s='+Regular_part+'&submit=Find')
time.sleep(5)
driver.find_element_by_xpath('/html/body/div/div[1]/div[2]/h1/a').click()
print("Opent new tab")
driver.execute_script("window.open ('https://google.com', 'new window')")
time.sleep(3)
print("back scn tab")
driver.switch_to_window(driver.window_handles[0])
time.sleep(3)
print("back google tab")
driver.switch_to_window(driver.window_handles[1])
driver.execute_script("window.close ('https://google.com', 'new window')")
z = input(":::")
if z == "y":
x = True
else:
x = False
After closing to window you have to Switch back to previous window again.
driver.execute_script("window.close ('https://google.com', 'new window')")
driver.switch_to.window(driver.window_handles[0])

Selenium Python code

This is my very first time trying to scrape data from a website using Selenium. Fortunately I have got Selenium and Chrome to coordinate and the desired website opens.Once it opens up, I want to tell Python to click 'SEARCH' leaving the empty box blank (next to contains) and then tell Python to export the results ' and save the xlsx file as result_file. I do not know why the snippet is blowing up. Please provide your kind assistance.
from selenium import webdriver
driver = webdriver.Chrome("C:\Python27\Scripts\chromedriver.exe")
driver.get("https://etrakit.friscotexas.gov/Search/permit.aspx")
number_option = driver.find_element_by_id("cplMain_btnSearch")
number_option.click()
search_button = driver.find_element_by_id("cplMain_btnExportToExcel")
search_button.click()
result_file = open("result_file.xlsx", "w")
driver.close()
result_file.close()
Looking at the source of that page, the ID of the search button is "cplMain_btnSearch" not "SEARCH". And the Export button is "cplMain_btnExportToExcel".
To expand the answer of Daniel Roseman, you also need to specify the download location
options.add_argument("download.default_directory=C:/Python27")
driver = webdriver.Chrome(chrome_options=options)
The file will then be stored in your python27 directory with the name RadGridExport.csv.

Selenium Webdriver failed when use window_handles

I am trying to handle Two Tab in Python Selenium webdriver with Chrome as browser.
I am getting result for find element by link text on first tab as well as second tab if I keep the Chrome Browser as selected window.[i.e Front Screen Process ]
When I change the control to new tab using
driver.switch_to_window(driver.window_handles[1])
and minimise the google chrome[i.e if I select any process other than Google Chrome].i get the error in finding the link text saying Element Not Found Exception for Second Tab only not on first Tab.
I am getting result on First Tab.
def DriverCreation():
try:
Driver = WebBase.initWebScraping(URL) # Methods visible Driver.driver and Driver.loggerDriverWait = Driver.EC
print "Driver Creation Successful"
return Driver
except:
print "Driver Initalisation Failed"
sys.exit(1)
if __name__ == '__main__':
URL = 'https://www.example.com/'
Driver = DriverCreation() # will Load first Tab with www.Example.com
aboutlink = Driver.driver.find_element_by_link_text('about')
aboutlink.send_keys(Keys.CONTROL + Keys.RETURN)
Driver.driver.switch_to_window(Driver.driver.window_handles[1])
contactLink = Driver.driver.find_element_by_link_text('contact')
print contactLink.text() #** getting error if i change the focus from Google Chrome and works fine if i keep the window focus on Google Chrome**
you can manage tab using following code.
driver.execute_script("window.open('"+url+"', '_blank');")
driver.switch_to_window(driver.window_handles[1])

How to switch to new window in Selenium for Python?

I am working on selenium automation project using Python.
I am facing an issue, which is handling multiple browser windows.
Scenario is as follows. When I click a link on the home page, a new window opens. In the newly opened window I cannot perform any actions, because the focus is still on the home page web driver.
Can anybody show me how to change focus from the background window to the newly opened window?
A possible solution is driver.switch_to.window(), but it requires the window's name. How to find out the window's name? If this is a wrong way to do this, can anybody give some code examples to perform this action?
You can do it by using window_handles and switch_to.window method.
Before clicking the link first store the window handle as
window_before = driver.window_handles[0]
after clicking the link store the window handle of newly opened window as
window_after = driver.window_handles[1]
then execute the switch to window method to move to newly opened window
driver.switch_to.window(window_after)
and similarly you can switch between old and new window. Following is the code example
import unittest
from selenium import webdriver
class GoogleOrgSearch(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
def test_google_search_page(self):
driver = self.driver
driver.get("http://www.cdot.in")
window_before = driver.window_handles[0]
print window_before
driver.find_element_by_xpath("//a[#href='http://www.cdot.in/home.htm']").click()
window_after = driver.window_handles[1]
driver.switch_to.window(window_after)
print window_after
driver.find_element_by_link_text("ATM").click()
driver.switch_to.window(window_before)
def tearDown(self):
self.driver.close()
if __name__ == "__main__":
unittest.main()
On top of the answers already given, to open a new tab the javascript command window.open() can be used.
For example:
# Opens a new tab
self.driver.execute_script("window.open()")
# Switch to the newly opened tab
self.driver.switch_to.window(self.driver.window_handles[1])
# Navigate to new URL in new tab
self.driver.get("https://google.com")
# Run other commands in the new tab here
You're then able to close the original tab as follows
# Switch to original tab
self.driver.switch_to.window(self.driver.window_handles[0])
# Close original tab
self.driver.close()
# Switch back to newly opened tab, which is now in position 0
self.driver.switch_to.window(self.driver.window_handles[0])
Or close the newly opened tab
# Close current tab
self.driver.close()
# Switch back to original tab
self.driver.switch_to.window(self.driver.window_handles[0])
Hope this helps.
window_handles should give you the references to all open windows.
this is what the documentation has to say about switching windows.
for eg. you may take
driver.get('https://www.naukri.com/')
since, it is a current window ,we can name it
main_page = driver.current_window_handle
if there are atleast 1 window popup except the current window,you may try this method and put if condition in break statement by hit n trial for the index
for handle in driver.window_handles:
if handle != main_page:
print(handle)
login_page = handle
break
driver.switch_to.window(login_page)
Now ,whatever the credentials you have to apply,provide
after it is loggen in. Window will disappear, but you have to come to main page window and you are done
driver.switch_to.window(main_page)
sleep(10)
We can handle the different windows by moving between named windows using the “switchTo” method:
driver.switch_to.window("windowName")
Click here to open a new window
Alternatively, you can pass a “window handle” to the “switchTo().window()” method. Knowing this, it’s possible to iterate over every open window like so:
for handle in driver.window_handles:
driver.switch_to.window(handle)

Categories

Resources