How do I switch to a popup window in the below selenium program. I've looked up for all possible solutions but haven't been able to get my head around them. Please help!!
from selenium import webdriver
from splinter import Browser
from selenium.webdriver.common.keys import Keys
handle = []
driver = webdriver.Firefox()
driver.get("http://example.com/test.aspx")
driver.find_element_by_link_text("Site Actions").click()
driver.find_element_by_link_text('Edit Page').click()
select = driver.find_element_by_id('ctl00_PlaceHolderMain_ctl35_ctl00_SelectResult')
for option in select.find_elements_by_xpath('//*[#id="ctl00_PlaceHolderMain_ctl35_ctl00_SelectResult"]/option'):
if option.text != 'Channel':
option.select() # select() in earlier versions of webdriver
driver.find_element_by_id('ctl00_PlaceHolderMain_ctl35_ctl00_RemoveButton').click()
parent_h = driver.current_window_handle
#click that activates the popup.
checkIn = driver.find_element_by_id('qaCheckin_anchor').click()
# click on the link that opens a new window
handles = driver.window_handles # before the pop-up window closes
driver.remove(parent_h)
driver.switch_to_window(handles.pop())
driver.implicitly_wait(10) # seconds
driver.find_element_by_xpath('/html/body/form/div[3]/table/tbody/tr[4]/td/table/tbody/tr[3]/td[2]/input').click()
driver.find_element_by_name('btnClose2').click()
driver.close();
# do stuff in the popup
# popup window closes
driver.switch_to_window(parent_h)
# and you're back
driver.switch_to_default_content()
in terms of browser, pop up is not a window, it is an alert. so, you should use following:
driver.switch_to_alert()
Related
Basic question. I want to use selenium to scroll to the bottom of the webpage but it is quitting shortly after scrolling. I want to stay on the page and be where I scrolled to. Here is the code:
def take_screenshots(url):
driver = webdriver.Chrome("/Users/jatinshekara/chromedriver")
driver.get(url)
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(5)
I used the time.sleep() function to make it sleep to make sure it was actually scrolling down. It is scrolling down but just quitting the web browser right after (basically what the code "driver.quit()" does).
Thanks in advance.
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_experimental_option("detach", True)
You'd want to add detach true and then add the options to your driver. Selenium automatically closes after it's operation.
driver = webdriver.Chrome("/Users/jatinshekara/chromedriver", options=chrome_options)
I am trying to parse a table from https://www.morningstar.de/de/screener/fund.aspx#?filtersSelectedValue=%7B%22sustainabilityRating%22:%7B%22id%22:%225%22%7D%7D&page=1&perPage=10&sortField=legalName&sortOrder=asc.
However, by opening the website with selenium I always get at first a pop-up, to close which I need to select type of user (radiobutton) and then click on "accept" button .
After I proceed these "clicks" with the help of python and selenium, the pop-up doesn't disappear sbut I can see that clicks were proceeded. It doesn't show any error (all the needed fields are selected and python script also doesn't throw anything).
Here is my code:
from selenium import webdriver
import time
browser = webdriver.Firefox()
url="https://www.morningstar.de/de/screener/fund.aspx#?filtersSelectedValue=%7B%22sustainabilityRating%22:%7B%22id%22:%225%22%7D%7D&page=1&perPage=10&sortField=legalName&sortOrder=asc"
browser.get(url)
time.sleep(10)
try:
radio_button = browser.find_elements_by_xpath('/html/body/div[2]/div[3]/div/div[2]/div/div[3]/div[1]/div[1]/fieldset/div[2]/label/span/span[1]')[0]
radio_button.click()
time.sleep(3)
accept_button=browser.find_element_by_id('_evidon-accept-button')
accept_button.click()
print("accepted")
except:
print(" something went wrong")
I need to close this pop-up in order to get access to the table, what am I doing wrong?
Example for radio button #finaprofessional > span:nth-child(1) or #finaprofessional > span:nth-child(2)
import time
from selenium import webdriver
def example():
firefox_browser = webdriver.Firefox()
firefox_browser.get("https://www.morningstar.de/de/screener/fund.aspx#?filtersSelectedValue=%7B%22sustainabilityRating%22:%7B%22id%22:%225%22%7D%7D&page=1&perPage=10&sortField=legalName&sortOrder=asc")
time.sleep(10) # wait for page to load
radio_button = firefox_browser.find_element_by_css_selector("#finaprofessional > span:nth-child(1)")
radio_button.click()
time.sleep(10)
accept_button = firefox_browser.find_element_by_id("_evidon-accept-button")
accept_button.click()
if __name__ == "__main__":
example()
there´s any python component
to do someting like this(this is java)
https://jxbrowser.support.teamdev.com/support/solutions/articles/9000013135-jxbrowser-selenium
i use python tkinter to open chrome instances on a click button,
i'd like to run selenium chrome instance in a python widget on a click button,
at the top of python gui app a button and when you click on it open the selenium chrome instance in a tkinter frame
is it possible to do something like that with a python GUI
thanks a lot
Yes you can, I would try something like this:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import WebDriverException
#Your paths and driver might be different.
CHROME_PATH = 'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe'
CHROMEDRIVER_PATH = 'chromedriver.exe'
WINDOW_SIZE = "1920,1080"
chrome_options = Options()
chrome_options.add_argument("--log-level=3")
chrome_options.add_argument("--headless") # This is optional, but faster than gui
chrome_options.add_argument("--window-size=%s" % WINDOW_SIZE)
chrome_options.binary_location = CHROME_PATH
browser = webdriver.Chrome(executable_path=CHROMEDRIVER_PATH, chrome_options=chrome_options)
url = "https://www.example.com" # Your url goes here.
browser.get(url)
# - You'll need to copy the button's xpath and place it in here.
element = WebDriverWait(browser, 10).until(
EC.presence_of_element_located((By.XPATH, 'copy_xpath_into_here')))
# click on button - You'll need to copy the button's xpath and place it in here, too.
selectElem=browser.find_element_by_xpath('copy_xpath_into_here').click()
I have the following Code that goes to a URL(www.example.com), and clicks on a link(Example 1). (This part works fine)
from selenium import webdriver
driver = webdriver.Firefox()
driver.get("https://www.example.com")
link = driver.find_element_by_link_text('Example 1')
link.click()
Now, when we click on 'Example 1' link, it opens a confirmation window, with 2 buttons: 'Yes I am authorized user to this site' and 'No I am a new visitor to this site'
So, I wish to click on 'Yes I am authorized user to this site' and then finally enter my log-in credentials.
I have written these 2 lines, just below the above code, for clicking on that button. But these don't work.
button = driver.find_element_by_name("'Yes I am authorized user to this site'")
button.click()
If it is an alert window, you need to use the Alert command.
#import Alert
from selenium.webdriver.common.alert import Alert
from selenium import webdriver
driver = webdriver.Firefox()
driver.get("https://www.example.com")
link = driver.find_element_by_link_text('Example 1')
link.click()
Alert(driver).accept()
#to dismiss alert
#Alert(driver).dismiss()
I think this would have solved your query.
Based on the comment conversation, I would recommend both using an XPATH search (instead of Name or Id) and waiting for elements to be clickable or loaded. When web-driving or web-scraping, pages may intentionally or accidentally load slowly and this can cause issues if you have pauses or waits either hard coded or non-existent. This snippet of code should allow you to search Google using Selenium and Chromedriver (you can modify the driver function to use Firefox or something else if you'd like):
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import ElementNotVisibleException
from selenium.webdriver.chrome.options import Options
from time import sleep
def init_driver(drvr_path):
chrome_options = Options()
chrome_options.add_argument("--disable-extensions")
driver = webdriver.Chrome(drvr_path+'chromedriver.exe',chrome_options=chrome_options)
driver.wait = WebDriverWait(driver, 5)
return driver
def lookup(query, driver=None, drvr_path=''):
driver = None
if driver is None:
driver = init_driver(drvr_path)
driver.implicitly_wait(45) # Allow up to 45 Seconds for page to load
driver.get("http://www.google.com")
try:
box = driver.wait.until(EC.presence_of_element_located((By.XPATH, """//*[#id="lst-ib"]""")))
box.send_keys(query)
sleep(3) # Let you see the window open
button = driver.wait.until(EC.element_to_be_clickable((By.XPATH,"""//*[#id="sblsbb"]/button""")))
try:
button.click()
except ElementNotVisibleException, s:
print "Error Handled: "+str(s)
button = driver.wait.until(EC.element_to_be_clickable((By.XPATH,"""//*[#id="sblsbb"]/button""")))
try:
button.click()
except:
print "Could not search Google..."
return
resp=driver.page_source.encode('utf-8')
with open(query+'.html','wb') as f:
f.write(resp)
print 'Wrote the File...'
except:
print("Box or Button not found in google.com")
driver.quit()
For example, if your Chromedriver.exe file was located in your default Python path, you could do something like: lookup('Selenium Python XPATH Examples') and it should download an HTML file of the Google Search results. If you already have a Driver initialized, you could of course pass that to it.
Hope this helps
Try this code, hope it will help you
from selenium import webdriver
import time
driver = webdriver.Chrome('path to chromedriver\chromedriver.exe')
driver.get('https://www.example.com')
driver.maximize_window()
link = driver.find_element_by_link_text('Example 1')
link.click()
handles =driver.window_handles # this will give window handles
driver.switch_to.window(handles[1])
button = driver.find_element_by_name("'Yes I am authorized user to this site'")
button.click()
I want to open quite a few URLs in different tabs using Selenium WebDriver & Python.
I am not sure what is going wrong:
driver = webdriver.Chrome()
driver.get(url1)
time.sleep(5)
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL+'t')
url2 = 'https://www.google.com'
driver.get(item2)
I looked up tutorials and it seems to me as though this code should do what I want. What actually happens is the browser opens, url1 opens as it should, a new tab opens as it should but url2 then loads in the original tab instead of the new one (even though the new tab appears to be the active one).
(I am using Chrome because when using Firefox I can't get it to load any URLs at all. Firefox opens but does not get the url requested. I have tried to find a solution to this but to no avail.)
Is there anything I can change in my code to get the new URL to open in the new tab?
Thanks for your help!
Here is a simple way, platform independent:
Code:
driver.execute_script("window.open('http://google.com', 'new_window')")
Switching back to the original tab:
Code:
driver.switch_to_window(driver.window_handles[0])
Checking the current title to be sure you are on the right page:
Code:
driver.title
For everything else, have fun!
There is a bug in ChromeDriver that prevents ctrl/command+T from working:
I can´t open new tab in ChromeDriver
What you can do, as a workaround, is to open a link in a new tab and then switch to a new window using the switch_to.window(). Working sample:
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome()
driver.get("https://www.google.com")
# open a link in a new window
actions = ActionChains(driver)
about = driver.find_element_by_link_text('About')
actions.key_down(Keys.CONTROL).click(about).key_up(Keys.CONTROL).perform()
driver.switch_to.window(driver.window_handles[-1])
driver.get("https://stackoverflow.com")
Now the last driver.get() would be performed in a newly opened tab.
An alternative way to open a new window is to use JavaScript and the window handler to switch between them.
driver = webdriver.Chrome()
# Open a new window
# This does not change focus to the new window for the driver.
driver.execute_script("window.open('');")
# Switch to the new window
driver.switch_to.window(driver.window_handles[1])
driver.get("http://stackoverflow.com")
# close the active tab
driver.close()
# Switch back to the first tab
driver.switch_to.window(driver.window_handles[0])
driver.get("http://google.se")
# Close the only tab, will also close the browser.
driver.close()
If you look at your browser while you're executing it will look like the new window has focus, but to the webdriver, it doesn't. Don't be fooled by the visual. Also remember to select a new window handler when you close a tab as it will set the driver.current_window_handle to
selenium.common.exceptions.NoSuchWindowException:
Message: no such window: target window already closed from unknown error: web view not found
(Session info: chrome=<Your version of chrome>)
(Driver info: chromedriver=<Your chrome driver version> (<string of numbers>),platform=<Your OS>)
on .close() and it will throw that error if you try to do stuff with the driver at that stage.
you need to maximize your chrome for this
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome()
driver.maximize_window()
driver.get("https://www.google.com/")
e = driver.find_element_by_tag_name("body")
ActionChains(driver).key_down(Keys.CONTROL).click(e).send_keys("k").key_up(Keys.CONTROL).perform()
here key_down(Keys.CONTROL) will hold down ctrl key, to get focus on page i am clicking body of the page, then click k