Handling window pop up with selenium [duplicate] - python-3.x

This question already has answers here:
How to allow or deny notification geo-location microphone camera pop up
(2 answers)
Closed 3 years ago.
I am currently working on a bot that logs into instagram, I currently have the script to log in and turn on notifications but when then I get a window pop the code does not click on allow. I have been stuck for quite some time. Thank you in advance for your help.
def allow_noti():
allow_noti = WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.XPATH,
"//button[contains(.,'Turn On')]")))
allow_noti.click()
allow_browser = WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.XPATH, '//*
[text()="Allow"]'))).click()
allow_browser.click()

Hope this helps
public static void main(String[] args)
{
ChromeOptions options = new ChromeOptions();
options.addArguments("--disable-notifications");
System.setProperty("webdriver.chrome.driver", "/home/users/ss/bb/chromedriver");
WebDriver driver =new ChromeDriver(options);
driver.get("http://google.com");
driver.manage().window().maximize();
}

Related

Chromdriver UserData configuration with Selenium

I have this simple function with Selenium
def config():
path = r'C:\Users\George\Desktop\Bot\User Data'
options = webdriver.ChromeOptions()
options.add_argument('user-data-dir=' + path)
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)
options.add_argument('--disable-blink-features=AutomationControlled')
driver = webdriver.Chrome(executable_path=r'C:\Users\George\Desktop\Bot\chromedriver.exe', chrome_options=options)
return driver
Which is working fine and as expected, But am making a simple bot to do tasks over a website that require sessions and cookies and so on.
So what I have to make each now and then, Is to copy the real browser User Data from:
C:\Users\George\AppData\Local\Google\Chrome\User Data
to my random location
'C:\Users\George\Desktop\Bot\User Data'
And it works fine, The reason am doing this is that I want to avoid login, and have the browser that I work with independent with the bot driver browser, And I Usually keep it laid down and never open while its doing my work.
Question
Is there a way, That I can automatically get the current session instant of copying Files (like get one open tab with all information attached )?
Is there a better way to do this? ( am sure there are plenty of better ways)
Thanks for the help, Any suggestion, Links, Blogs are much appriciated.
You won't be required to copy the real browser User Data from:
C:\Users\George\AppData\Local\Google\Chrome\User Data
to:
C:\Users\George\Desktop\Bot\User Data
each now and then if you point user-data-dir to the real google-chrome User Data directory as follows:
def config():
options = webdriver.ChromeOptions()
# next line you need to replace the random location with actual browser data location
options.add_argument(r"--user-data-dir=C:\Users\George\AppData\Local\Google\Chrome\User Data")
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)
options.add_argument('--disable-blink-features=AutomationControlled')
driver = webdriver.Chrome(executable_path=r'C:\Users\George\Desktop\Bot\chromedriver.exe', chrome_options=options)
return driver
References
You can find a couple of relevant detailed discussion in:
Selenium: Point towards default Chrome session

Webdriver.io/Selenium tests fail when the window is in the background on Chrome 87

I've just upgraded to the latest version of Chrome 87. My Webdriver.io/Selenium tests used to run fine regardless of if the Chrome window was in the foreground or the background. Now, after upgrading, the tests pass if the window is in the foreground, but not if it's in the background.
I'm not minimizing the Chrome window running my tests. I'm just pressing Alt+Tab so that my IDE is in front of Chrome and it's behind.
I know Chrome 87 has a new "feature" where it uses less CPU if it's not in the foreground. Is there a way to turn this off with either Chrome or Chromedriver settings?
It seems that my test is finding the button to click on, but Chrome isn't registering the click.
This is a bug in Chrome 87:
https://bugs.chromium.org/p/chromedriver/issues/detail?id=3641&sort=-id
Workaround
Node JS
The workaround is to set the "localState" in Webdriver.io's desiredCapabilities like the below in Node.JS/Chimpy:
chimpOptions.webdriverio.desiredCapabilities = {
chromeOptions: {
args: ["--no-sandbox", ...],
prefs: {...}
},
localState: {
"browser.enabled_labs_experiments": ["calculate-native-win-occlusion#2"],
},
},
...
};
Java
ChromeOptions options = new ChromeOptions();
HashMap<String, Object> chromeLocalStatePrefs = new HashMap<String, Object>();
List<String> experimentalFlags = new ArrayList<String>();
experimentalFlags.add("calculate-native-win-occlusion#2");
chromeLocalStatePrefs.put("browser.enabled_labs_experiments", experimentalFlags);
options.setExperimentalOption("localState", chromeLocalStatePrefs);
Previous Answer
The other workaround is to leave a small lip of the background Chrome window underneath your active browser/IDE/etc.
In the image below, you can see a small amount of the Chrome window running the test.
the latest chrome - chromedriver has resolved this issue
For now, you can use this workaround:
Download the previous version of Chrome. This one is for version 81: https://commondatastorage.googleapis.com/chromium-browser-snapshots/index.html?prefix=Win/735601/
See other versions by link: https://commondatastorage.googleapis.com/chromium-browser-snapshots/index.html?prefix=Win/
Specify a direct path to the chrome.exe executable via parameter "chrome_binary":
java -jar selenium-server-standalone-3.141.59.jar -role node -hub http://192.168.88.42:4444/grid/register -browser browserName=chrome,platform=ANY,maxInstances=60,seleniumProtocol=WebDriver,applicationName=test4,chrome_binary=C:\Users\PC\Downloads\Win_735601_chrome-win\chrome-win\chrome.exe -maxSession 60
Enjoy using an older version of Chrome.
I am using C# and facing same issue. I have added a workaround by adding minimize and maximize window like below. Usually we assert page title, hence the switching to window is bringing the focus and other test actions are passing. below one is the workaround for taking screenshot failure.
private void MinMaxWindow(ChromeDriver driver)
{
driver.Manage().Window.Minimize();
driver.Manage().Window.Maximize();
}
Edit,
Dev has given workaround like below.
Java
ChromeOptions options = new ChromeOptions();
HashMap<String, Object> chromeLocalStatePrefs = new HashMap<String, Object>();
List<String> experimentalFlags = new ArrayList<String>();
experimentalFlags.add("calculate-native-win-occlusion#2");
chromeLocalStatePrefs.put("browser.enabled_labs_experiments", experimentalFlags);
options.setExperimentalOption("localState", chromeLocalStatePrefs);
Python
chrome_options = webdriver.ChromeOptions()
experimentalFlags = ['calculate-native-win-occlusion#2']
chromeLocalStatePrefs = { 'browser.enabled_labs_experiments' : experimentalFlags}
chrome_options.add_experimental_option('localState',chromeLocalStatePrefs);
chromeOptions.addArguments("--disable-backgrounding-occluded-windows");
I ran into same issue since updating to Chrome 87 and chrome driver 87.
Found the fix here:
https://support.google.com/chrome/thread/83911899?hl=en

Google consent automatic accepting

I am new newbie to Selenium Driver. I am trying to click 'Agree' button automatically on google search pop up using selenium driver interface. I am using python and the code is:
driver.get(f"https://www.google.com")
driver.find_element_by_xpath('//*[#id="introAgreeButton"]').click()
But this is not working. Can someone help me?google auto pop up for consent
this worked for me:
options = webdriver.ChromeOptions()
options.add_argument("start-maximized")
options.add_argument('disable-infobars') #attempting to disable infobar
browser=webdriver.Chrome(options=options,
executable_path=r'/usr/local/bin/chromedriver')
browser.get('http://www.google.com')
browser.switch_to.frame(browser.find_element_by_xpath("//iframe[contains(#src,
'consent.google.com')]"))
time.sleep(5)
browser.find_element_by_xpath('//*[#id="introAgreeButton"]/span/span').click()
browser.find_elements(By.XPATH, "//form //div[#role = 'button' and #id =
'introAgreeButton'").click()

Python: Log into the website using selenium?

I want to login to the following website:
https://www.investing.com/equities/oil---gas-dev-historical-data
Here is what I have tried so far:
from selenium import webdriver
profile = webdriver.FirefoxProfile()
profile.set_preference("browser.download.folderList", 2)
profile.set_preference("browser.download.manager.showWhenStarting", False)
profile.set_preference("browser.download.dir", './ogdc.csv')
profile.set_preference("browser.helperApps.neverAsk.saveToDisk", "application/x-gzip")
driver = webdriver.Firefox(firefox_profile=profile)
driver.get('https://www.investing.com/equities/oil---gas-dev-historical-data')
driver.find_element_by_class_name("login bold")
driver.find_element_by_id('Email').send_keys('myemail')
driver.find_element_by_id('Password').send_keys('mypass')
driver.find_element_by_partial_link_text("Download Data").click()
But I get following Exception:
NoSuchElementException
How can I login to the above website?
You need click Sign in first to bring up the login popup, try the following code:
driver.get('https://www.investing.com/equities/oil---gas-dev-historical-data')
driver.find_element_by_css_selector("a[class*='login']").click()
driver.find_element_by_id('loginFormUser_email').send_keys('myemail')
driver.find_element_by_id('loginForm_password').send_keys('mypass')
driver.find_element_by_xpath("//div[#id='loginEmailSigning']//following-sibling::a[#class='newButton orange']").click()
From what I can tell, you need to click the Sign In button („login bold”) in order to open the popup. That one is not part of the initial DOM load and need some time to show up. So basically, wait for #Email and #Password to get visible.
You should be able to use an explicit wait for this.

Chrome alert pop up not detected in Selenium

I am having issues with handling Authentication pop up in Chrome via Selenium.
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
driver = webdriver.Chrome()
driver.get('URL')
time.sleep(5)
alert = driver.switch_to_alert()
alert.send_keys('Username')
alert.send_keys(Keys.TAB)
alert.send_keys('Password')
This returns an error--
"selenium.common.exceptions.NoAlertPresentException: Message: no alert open"
Alternatively, I also tried the following code:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
driver = webdriver.Chrome()
driver.get('https://Username:Password#URL')
The second code works partially-
In Chrome the user is logged in but the page does not load. Only a blank page is displayed. Once the blank page is loaded, i passed only the URL(without user credentials) and it works fine.
In Firefox, the webpage loads perfectly.
Basically, the issue is with Chrome.
Any help is appreciated.
Thanks!
The second code you have tried is correct with a slight mistake.
public void loginToSystem(String username,String password, String url){
driver = webdriver.Chrome()
driver.get("https://"+username+":"+password+"# "+URL);
}
First try to wait for alert present.
wait = WebDriverWait(driver, 10)
wait.until(EC.alert_is_present())
if alert is present then only move forword to next step.
And also can you please check the screenshot if alert is actually present when testcase is failing.

Resources