ubuntu python selenium -- close terminal - python

I'm doing some testing on a Ubuntu terminal (14.04) using python (2.7) and selenium. I have created code that will open a browser, enter username and password information into the respective fields, and keep the browser open for one hour. The problem is, a python terminal is opened when code is run. When the browser is manually closed, the blank terminal remains. How can I get the terminal to disappear when the browser is manually closed?
Code:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
import sys
driver = webdriver.Firefox()
driver.maximize_window()
driver.get("http://example.com")
inputElement = driver.find_element_by_id("username")
inputElement.send_keys('...')
inputElement = driver.find_element_by_name("password")
inputElement.send_keys('...')
inputElement.send_keys(Keys.ENTER)
while 1:
time.sleep(3600)
try:
b = browser.find_by_tag("body")
except:
sys.exit()
I should mention that I'm executing this script using a .desktop file.

you can ping the browser once every second during the "sleep" time
i = 0
while i < 3600:
browser.title
time.sleep(1)
i += 1
b = browser.find_by_tag("body")

Related

the page closes as soon as it opens using webdriver

enter image description here
code:
chrom_driver_pat = "C:\pythondriver\chromedriver"
driver = webdriver.Chrome(executable_path=chrom_driver_pat)
driver.get("https://instagram.com/%22)
terminal:
c:\Users\arda6\Desktop\pyhton_kursu\selenium\setup.py:7: DeprecationWarning: executable_path has been deprecated, please pass in a Service object
driver = webdriver.Chrome(executable_path=chrom_driver_pat)
DevTools listening on ws://127.0.0.1:56927/devtools/browser/7ce68db7-9314-4927-9718-ca24f43ec2e0
When I run the code here, the instagram site should open and stay open, but when I run it, the site closes as soon as it opens. What should I do?
the page closes as soon as it opens
It shouldn't stay open with the code you've provided.
For example:
driver.get("https://instagram.com/%22)
Should be:
driver.get("https://instagram.com/%22")
There is one more thing you should do to make sure it works:
from time import sleep
#your code
#here
sleep(15)
This will make sure the code doesn't stop working after it's done what you wanted it to do for another 15 seconds.
If you want to keep the Chrome Tab alive after code execution. Consider to use Options.
from selenium.webdriver.chrome.options import Options
# Don't Close Chrome
chrome_options = Options()
chrome_options.add_experimental_option("detach", True)
# Initialize Chrome
driver = webdriver.Chrome(options=chrome_options)

Google chrome closes after adding the excel code but works without the excel code

I'm pretty new to Python and automation. I'm trying to automate logging in to a web page and add data which I've extracted from excel to a text box on the web page.
Opening the web pages works fine without adding the piece of code below.
import xlwings as xw
wb = xw.Book('myExcel.xlsx')
alertNumber = wb.app.selection
Before adding the above code chrome opens and goes to every URL and at the final page it stays open untill i click on close, but after adding the above piece of code the chrome closes after executing everyline.
Can someone explain what is missing as Im pretty new to coding.
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
import xlwings as xw
wb = xw.Book('myExcel.xlsx')
alertNumber = wb.app.selection
uname = "dummy#example.com"
pword = "Th!s!smydummypa$$w0rd"
supportPortal = "https://url1.com"
openCase = "https://url2.com"
Path = "c:/chromedriver.exe"
driver = webdriver.Chrome(Path)
driver.get(supportPortal)
driver.find_element(By.NAME, "email").send_keys(uname)
driver.find_element(By.ID, "remember-cb").click()
driver.find_element(By.CSS_SELECTOR, ".submit-btn").click()
print("Username added")
time.sleep(2)
driver.find_element(By.ID, "password-sign-in").send_keys(pword)
driver.find_element(By.CSS_SELECTOR, ".submit-btn").click()
print("Password added")
print("Starting to wait")
time.sleep(20)
print("Wait is over")
driver.get(openCase)
driver.find_element(By.NAME, "alert_number").send_keys(alertNumber)
Thanks for the support, guys. I think I found the answer. webdriver closes the chrome session as soon as it finishes executing the code. Therefore, I added a
time.sleep(30)
to keep the chrome open until I get sufficeint time to do the changes.

How to keep Firefox Log in status when using Selenium?

I want to keep Firefox Login status when using Selenium WebDriver (geckodriver). I used below python code:
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
import time
try:
fp = webdriver.FirefoxProfile('C:/Users/admin/AppData/Roaming/Mozilla/Firefox/Profiles/mow8ff69.selenium')
options = Options()
options.headless = False
browser = webdriver.Firefox(fp, options=options)
browser.get('https://stackoverflow.com/users/login');
time.sleep(2)
txt_username = browser.find_element_by_id('email')
txt_username.clear()
txt_username.send_keys('***#gmail.com') #replace with your own username
time.sleep(1)
txt_password = browser.find_element_by_id('password')
txt_password.clear()
txt_password.send_keys('*****') #replace with your own password
time.sleep(1)
txt_password.submit()
time.sleep(10)
except Exception as ex:
print('Error: {0}'.format(ex))
finally:
browser.quit()
As shown above, I have been using a User Profile created by "Firefox -p". However, after running above code, when I reopen Firefox using that profile and then go to stackoverflow.com, I'm still not logged in.
So it looks like that Selinum WebDriver actually runs firefox in a "sandbox" which cannot write to the User Profile at all? I know that ChromeDriver has a "--no-sandbox" option but it doesn't seem to be available in geckodriver? Is there any workaround?
I cannot switch to ChromeDriver because there is another bug with it: the "--headless" option actually conflicts with "--user-data-dir" option whereas I really need both.

Python selenium not executing bookmarklet properly

I have a bookmarklet that executes successfully from the browser:
javascript:!function(a){var b=document.createElement("textarea"),c=document.getSelection();b.textContent= a,document.body.appendChild(b),c.removeAllRanges(),b.select(),document.execCommand("copy"),c.removeAllRanges(),document.body.removeChild(b);}(<text here>);
When I try to execute this through the Selenium webdriver using Python it is returning None. Any thoughts on how to get this to copy the text to the clipboard like the bookmarklet? Full code is below:
from selenium import webdriver
chromeOptions = webdriver.ChromeOptions()
chromeOptions.add_experimental_option('useAutomationExtension', False)
driver = webdriver.Chrome(options=chromeOptions, desired_capabilities=chromeOptions.to_capabilities())
driver.implicitly_wait(5)
driver.get("websitehere")
js = """javascript:!function(a){var b=document.createElement("textarea"),c=document.getSelection();b.textContent= a,document.body.appendChild(b),c.removeAllRanges(),b.select(),document.execCommand("copy"),c.removeAllRanges(),document.body.removeChild(b);}(<texthere>);
"""
print(driver.execute_script(js))
After some reading online it looks this type of work flow is blocked due to security concerns. I was seeing this error in the console chrome document.execCommand(‘cut’/‘copy’) was denied because it was not called from inside a short running user-generated event handler.
Note that below did not work on Firefox only Chrome may start failing on Chrome in the next couple versions.
from selenium import webdriver
import time
import pyperclip
import pyautogui
driver = webdriver.Chrome(executable_path=r'C:\\Path\\To\\chromedriver.exe')
driver.get("https://www.google.com")
time.sleep(2)
pyautogui.hotkey('ctrl', 'shift', 'j')
time.sleep(2)
js2 = """
var testCopy = function(a) {
var b=document.createElement("textarea"), c=document.getSelection();
b.textContent = a,
document.body.appendChild(b)
c.removeAllRanges()
b.setAttribute("id", "testid")
b.select()
document.execCommand("copy")
console.log('copy success', document.execCommand('copy'));
c.removeAllRanges();
}
testCopy("ThisText")
"""
driver.execute_script(js2)
time.sleep(1)
a = pyperclip.paste()
print(a)

why blank page opens in firefox when run with selenium for the first time?

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Firefox()
#driver.set_preference("browser.startup.homepage_override.mstone", "ignore")
driver.get("https://url.aspx/")
username = driver.find_element_by_name("SchSel$txtUserName")
username.clear()
username.send_keys("username")
username.send_keys(Keys.RETURN)
password = driver.find_element_by_name("SchSel$txtPassword")
password.clear()
password.send_keys("pass")
password.send_keys(Keys.RETURN)
driver.get("https://.aspx")
assert "Welcome" in driver.page_source
driver.close()
I am running selenium for the first time .How many times I try blank page opens in fireFox
selenium.common.exceptions.WebDriverException: Message: The browser appears to have exited before we could connect. If you specified a log_file in the FirefoxBinary constructor, check it for details.
I think I had a similar problem and used the info at this link to help:
https://stackoverflow.com/a/30103931/6582364
Basically it suggests using xvfb and pyvirtualdisplay which wraps the firefox browser. Link also contains sample code. Doesn't take too long to install and get running but worked for me.
Hope this works for you too.

Categories