Firefox headless mode with Selenium: why does it remember old access? - python

I'm trying to make up a system in order to automate sign-in procedure on booking.com.
What I want to accomplish is that when I visit the following page: https://join.booking.com/?lang=it , the browser have to show me the sign-in form as I was visiting it for the first time.
Unfortunately it doesn't happen, somehow Firefox remembers that I have already done something on this page and show me the "continue to register" page. I read that selenium always has a fresh start, I have disabled cache memory, form auto-fill but still I can't get it done.
Any suggestions? Maybe some Firefox preference should be set, like cache memory ecc...
Working with python 2.7.9, selenium 3.141.0 and geckodriver 0.26.0
import time
import sys
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
def initialize_driver():
options = Options()
options.headless = True
options.add_argument("--private")
print(options)
driver = webdriver.Firefox(executable_path='/Users/giovanni/Documents/IA_beta_v0.0.0/tools/geckodriver', options=options)
try:
driver.get("https://www.google.com")
print("Driver successfully initialized\n")
except:
print("Error while initializing driver\n")
return driver
def close_driver(driver):
try:
driver.close()
print("Driver closed correclty\n")
except:
print("An error occured when trying to shut down driver\n")
def new_registration():
print("Enter name: ")
name = raw_input()
print("Enter surname: ")
surname = raw_input()
print("Enter email: ")
email_address = raw_input()
print("\nPlease check the information you have entered:\n")
print("Name = %s;\n" %name)
print("Surname = %s;\n" %surname)
print("Email address = %s;\n" %email_address)
print("Are these information correct?(y/n)\n")
user_answer = raw_input()
if user_answer == 'y':
print("Proceeding with entablishing connection with Booking.com\n")
elif user_answer == 'n':
print("What information would you like to change?\n")
print("\t-name;\n")
print("\t-surname;\n")
print("\t-email;\n")
user_answer = raw_input()
if user_answer == 'name':
print("You have choose to modify the name for the registration\n")
name = substitute_info_registration(1,name)
print("\nNew name is %s\n" %name)
elif user_answer == 'surname':
print("You have choose to modify the surname for the registration\n")
surname = substitute_info_registration(2,surname)
print("\nNew name is %s\n" %surname)
elif user_answer == 'email':
print("You have choose to modify the email address for the registration\n")
email_address = substitute_info_registration(3,email_address)
print("\nNew name is %s\n" %email_address)
else:
print("Wrong input. Please enter one of the three options\n")
else:
print("Wrong input. Please enter one of the two options\n")
booking_registration_procedure(name,surname,email_address)
def substitute_info_registration(flag,info):
if flag == 1:
print("Current name is %s. Which is going to be the new name? " %info)
user_answer = raw_input()
print("New name is %s.\n" %user_answer)
elif flag == 2:
print("Current surname is %s. Which is going to be the new surname? " %info)
user_answer = raw_input()
print("New surname is %s.\n" %user_answer)
elif flag == 3:
print("Current email address is %s. Which is going to be the new email address? " %info)
user_answer = raw_input()
print("New email address is %s.\n" %user_answer)
return user_answer
def booking_registration_procedure(name,surname,email_address):
print("Initializing driver...\n")
firefox = initialize_driver()
#STEP 1
firefox.get('https://join.booking.com/?lang=it')
#source = firefox.page_source
try:
firefox.save_screenshot('/Users/giovanni/Documents/IA_beta_v0.0.0/screenshot/first_page.jpg')
print("Screenshot taken correctly\n")
except:
print("Can't take first screenshot\n")
try:
name_surname_form = firefox.find_element_by_id('ultranet_label_input_0')
name_surname_form.send_keys(name + " " + surname)
email_address_form = firefox.find_element_by_id('ultranet_label_input_1')
email_address_form.send_keys(email_address)
firefox.save_screenshot('/Users/giovanni/Documents/IA_beta_v0.0.0/screenshot/first_page_after_filling_form.jpg')
except:
print("Can't fill form with name, surname and email address\n")
close_driver(firefox)
exit(1)
try:
continue_button = firefox.find_elements_by_name('save')
print continue_button
continue_button[0].click()
time.sleep(2)
firefox.save_screenshot('/Users/giovanni/Documents/IA_beta_v0.0.0/screenshot/first_page_after_clicking_button.jpg')
except:
print("Can't click continue button\n")
close_driver(firefox)

Related

Random Dictionary Login System Python

I want to create the login system that will use random dictionary.The problem is accessing the elements of the dictionary after making it select random elements.I will continue trying to find the answer, but I want to post this problem here as there could be someone else with the similar problem and this could help them, and you may answer before I find the right way of access.
import time
import random
import string
d = {
'l1' : 'p1', 'l2' : 'p2'
}
d1 = random.choice(list(l.items()))
def d2(l, p):
d_l = print(l)
d_p = input("Enter the Answer: ")
if d_p == p:
print("Login Successful.")
else:
print("Your Answer was not correct.")
print("Process will be terminated")
time.sleep(5)
d2(#Here is the Problem)
I tried accessing using iter, although I know it's impossible.
Solution for this Problem is:
import time
import random
d = {
'l1' : 'p1', 'l2' : 'p2'
}
key, value = random.choice(list(d.items()))
def d2(l, p):
d_l = print(l)
d_p = input("Enter the Answer: ")
if d_p == p:
print("Login Successful.")
else:
print("Your Answer isn't correct.")
print("Process will be terminated")
time.sleep(5)
d2(key, value)
def getlogins():
from requests import get
return get(url).text
logins = getlogins()
logins = logins[:-1]
username = input("Username:")
username = str(username)
password = input("Password: ")
password = str(password)
if password == logins[username]:
print("Logged in!")
else:
print("Wrong password or username")
def getlogins(url):
from requests import get
return get(url).text
logins = getlogins()
logins = logins[:-1]
username = input("Username:")
username = str(username)
password = input("Password: ")
password = str(password)
if password == logins[username]:
print("Logged in!")
else:
print("Wrong password or username")

main function runs twice, but works normally second call in python

I'm writing a automation script which based on user input executes other scripts whose methods are called and fed the input as arguments.
Problem is, when the main script is first run, the user is asked for information twice.
After the second run, the script works as intended for the next runs without error.
import of function in main script
from spw import seaSec
#main function to call for pw resets
def menu ():
con = ""
while (con!= "no"):
empID = input("What is the employee ID ")
last4 = input("What are ")
answer = input("Which website would you like to go to ").lower()
if answer == "sea":
seaSec(empID, last4)
#Will add once OmniCo script works
#elif answer == "omni"
#omniCo(empID, last4)
con = input("Need help with anything else? (Enter y or n) ")
if con == "n":
quit()
menu()
def seaSec(empID, last4):
from **** import createTicket
PATH = "C:\Program Files (x86)\chromedriver.exe"
driver = webdriver.Chrome(PATH)
driver.get("http://wodapp/SecurityServices/Admin/FindUser.aspx")
driver.minimize_window()
#Input employee ID input to verify
ID = driver.find_element(By.ID, 'ContentPlaceHolder1_sapPersonnelNumberTextBox')
ID.send_keys(empID)
#submit information
Sub = driver.find_element(By.ID, "ContentPlaceHolder1_submitImageButton")
Sub.click()
#Hold SSN for verification, then compare to user input
VER = driver.find_element(By.ID, 'ContentPlaceHolder1_userRepeater_editImageButton_0')
VER.click()
num= driver.find_element(By.ID, "ContentPlaceHolder1_").get_attribute('value')
while cont != "0":
if (last4 == num):
cont = 0
break
elif (last4 != num):
print("Value does not match")
return False
firstName = driver.find_element(By.ID, "ContentPlaceHolder1_firstNameTextBox").get_attribute('value')
lastName = driver.find_element(By.ID, "ContentPlaceHolder1_lastNameTextBox").get_attribute('value')
fullName = firstName + " " + lastName
select = Select(driver.find_element(By.ID, "ContentPlaceHolder1_homeParkDropDownList"))
parkID = select.first_selected_option.text
driver.back()
choice = input("basic or xstore? ").lower()
def spw():
Reset = driver.find_element(By.ID, "ContentPlaceHolder1_userRepeater_resetPasswordImageButton_0")
Reset.click()
print(createTicket("pwd", parkID, empID, fullName, "Sea-Port" ))
driver.quit()
def xpw():
xStore = driver.find_element(By.ID, "ContentPlaceHolder1_userRepeater_manageXStoreImageButton_0")
xStore.click()
choice = input("Unlock or PW? ").lower()
if choice == "unlock":
unlock = driver.find_element(By.ID, "ContentPlaceHolder1_unlockImageButton")
unlock.click()
print(createTicket("unlock", parkID, empID, fullName, "Xstore"))
elif choice == "pw":
reset = driver.find_element(By.ID, "ContentPlaceHolder1_resetPasswordImageButton")
reset.click()
print(createTicket("pwd", parkID, empID, fullName, "Xstore"))
if choice == "basic":
spw()
elif choice == "xstore":
xpw()
driver.quit()

Saving multiple user inputs in text file in Python

I am fairly new to Python and am trying this project. I need to store usernames and passwords in a text file ( to create a database). I have used the pickle module. The code I've tried erases previously-stored data every time I run the code.
I have understood that I have to append data to the file instead of writing to it but I don't know how. How can I correct the code?
import pickle
# pickle mod converts obj into byte stream to store in database
import time
def load_Dictionary():
try :
with open("UserDict.txt" , "rb") as ufile :
return pickle.load(ufile)
except IOError :
with open("UserDict.txt" , "ab") as ufile :
pickle.dump(dict() , ufile)
return dict()
def save_Dictionary(UserDict):
with open("UserText.txt" , "wb") as ufile :
pickle.dump(UserDict , ufile)
def new_User_Login():
userDict = load_Dictionary() # dictionary is loaded
checkUserAcc = input("Are you a new user ( Yes or No ) ? ")
# insert buttons for yes no
# tk.Button(window, text="", command=password_generator).pack(pady=10)
if (checkUserAcc == "Yes" or checkUserAcc == "yes" or checkUserAcc == "YES"):
username = input("Please enter your username : ")
Root_password = input ("Please enter your password :")
if ( username in userDict):
print("Username you entered is not available")
new_User_Login()
else :
userDict[username] = Root_password
print("Login Successful!")
save_Dictionary(userDict) # saves new login info
time.sleep(2.0)
elif (checkUserAcc == "No" or checkUserAcc == "no" or checkUserAcc == "NO") :
user_login()
else :
print("Invalid input! Try Again.")
new_User_Login()
def user_login():
global username
global Root_password
global tries
login_Username = input("Enter your Username : ")
login_Password = input("Enter your Password : ")
UserDict = load_Dictionary()
if ( tries < 5):
for key in UserDict:
if (login_Username == key and login_Password == UserDict[key]):
print("You have successfully logged in !")
else :
print("Login Failed! Please try again")
tries = tries + 1
user_login()
if( tries >= 5 ):
print("You have attempted login too man times. Try again later. ")
time.sleep(30.0)
tries = 1 # reset tries counter
user_login()
global tries
tries=1
new_User_Login()
It appears you were using "wb" instead of "ab" in this function, which caused the file to reset everytime you wished to save to it. Also, The filename should be "UserDict", instead of "UserText".
def save_Dictionary(UserDict):
with open("UserDict.txt" , "ab") as ufile:
pickle.dump(UserDict , ufile)

Python login limit

i'm trying to implement login attempt system to my current code, but i don't know where i should tick it. Can someone suggest anything? I would like to give three attempts to login, if user fails to login, system will lock user out. I just dont know where to position the code properly.
granted = False
def grant():
global granted
granted = True
def login(name,password):
success = False
file = open("user_details.txt","r")
for i in file:
a,b = i.split(",")
b = b.strip()
if(a==name and b==password):
success=True
break
file.close()
if(success):
print("Login Succesful")
grant()
else:
print("wrong username or password")
The better way to do this problem is by having a JSON file instead of a txt file. You can have the file in this format:
{
"username": {
"password": "",
"attempts": 0,
}
}
In the login() function increment and write the count of attempts if the password is wrong.
And before the function begins read the JSON and check if the attempts value is greater than 3. If it is greater send an appropriate message else to continue the login action and ask for the password.
Your code had some minor errors which I have handled here:
import re
granted = False
def grant():
global granted
granted = True
def login(name,password):
success = False
file = open("user_details.txt","r")
for i in file:
if i.count(',') > 0: # check whether i has at least one ','
a,b = i.split(",")
b = b.strip()
if(a==name and b==password):
success=True
break
file.close()
if(success):
print("Login Succesful")
grant()
else:
print("wrong username or password")
def register(name,password):
file = open("user_details.txt","a")
file.write( "\n"+name[0]+","+password) # name is an array so only the first element is stored.
file.close()
grant()
def access(option):
global name
if(option=="login"):
name = input("Enter your name: ")
password = input("enter your password: ")
login(name,password)
else:
print("Enter yor name and password to register")
name = input("Please enter your name: ").lower().split()
if len(name) > 1:
first_letter = name[0][0]
three_letters_surname = name[-1][:3].rjust(3, 'x')
name = '{}{}'.format(first_letter, three_letters_surname)
print(name)
while True:
password = input("Enter a password: ")
if len(password) < 8:
print("Make sure your password is at lest 8 letters")
elif re.search('[0-9]',password) is None:
print("Make sure your password has a number in it")
elif re.search('[A-Z]',password) is None:
print("Make sure your password has a capital letter in it")
else:
print("Your password seems fine")
break
register (name,password)
def begin():
global option
print("Welcome to Main Menu")
option = input("Login or Register (login,reg): ")
if(option!="login" and option!="reg"):
begin()
begin()
access(option)
if(granted):
print("Welcome to main hub")
print("#### Details ###")
print("Username:",name)

Password - Login not working Python

I just finished Coursera's Python for Everybody 1st course.
To practice my skills, I decided to make a password and username login. Whenever I create a username, I get my user set error which says 'Invalid credentials'. Here is my code.
import time
import datetime
print ('storingData')
print("Current date and time: ", datetime.datetime.now())
while True:
usernames = ['Admin']
passwords = ['Admin']
username = input ('Please enter your username, to create one, type in create: ')
if username == 'create':
newname = input('Enter your chosen username: ')
usernames.append(newname)
newpassword = input('Please the password you would like to use: ' )
passwords.append(newpassword)
print ('Temporary account created')
continue
elif username in usernames :
dataNum = usernames.index (username)
cpasscode = passwords[dataNum]
else:
print ('Wrong credentials, please try again')
continue
password = input ('Please enter your password: ')
if password == cpasscode:
print ('Welcome ', username)
The code as it appears in my editor
In your code, you have initialized your usernames array right after the while statement. This means that every time it loops back to the beginning, it re-initializes, losing anything that your previously appended. If you move the array initialization outside of the loop, it should work as expected.
This works for python 3. for python 2 you must take input differently refer: Python 2.7 getting user input and manipulating as string without quotations
import time
import datetime
names = ['Admin']
pwds = ['Admin']
while True:
name = input('Name/create: ')
if name == "create":
name = input('New Name: ')
pwd = input('New Pwd : ')
names.append(name)
pwds.append(pwd)
continue
elif name in names:
curpwdindex = names.index(name)
print(names)
curpwd = pwds[curpwdindex]
givenpwd = input('Password: ')
if givenpwd == curpwd:
print("Welcome")
break
else:
print("Inavlid Credential")
else:
print("Wrong Choice")
continue

Categories

Resources