I wrote this script with Python tkinter and Selenium.
I create a button, when we click on it, 2 functions have to be executed. But I don't know why, it doesn't work well, only the first one: login() is executed and the second one: kalk() will not be executed.
If I put all the lines of the 2 functions in only one function, it works until the end without any problem.
Why does the below code not work ?
Here is the code (only a part of the program):
def login():
boutoncount.config(state='disabled')
browser = webdriver.Chrome(executable_path=r"C:\Users\Bat02\Desktop\Python\Selenium Test\chromedriver.exe")
browser.get('url')
time.sleep(10)
login= browser.find_element_by_id("UserID")
pwd = browser.find_element_by_id("Password")
confirm= browser.find_element_by_id("LogIn")
login.send_keys(loginentry.get())
pwd.send_keys(pwdentry.get())
time.sleep(3)
confirm.click()
def kalk():
time.sleep(10)
kalknum= browser.find_element_by_id("txt_Kalk")
eigkalkuncheck=browser.find_element_by_id("chk_Kalk")
eigkalkuncheck.click()
kalknum.send_keys(user_entries[0].get())
boutoncount=Button(fenetre,text="count",width=800,height=1,bg="white", font="bold",bd=5, command=lambda:[login(),kalk()])
boutoncount.pack(side=BOTTOM)
Thank you !
Related
I'm trying to use SendMouseWheelEvent to pass mouse scrolls into the browser, but it is only working on the first page load. Any subsequent pageloads after that, it does not work, unless the browser is interferred with actual mouse scroll.
I've prepared the following script. The "errorrep" is actually the name of the script itself, as "errorrep.py", into which I'm assigning the browser as "mybrowser".
How can I have the browser correctly work with SendMouseWheelEvent on subsequent pageloads?
cefpython version is 66.1.
"""
SendMouseWheelEvent is correctly performed on the first page load. On any pageloads after that, it does not seem to work, but it works again when the actual mouse device performs a scroll on the webpage
'# test 1' which does a javascript code 'scrollBy', works on every pageload.
'# test 2' which does a SendMouseWheelEvent, only works on first page load.
"""
from cefpython3 import cefpython as cef
import time
from threading import Thread
import errorrep
mybrowser = None
def main():
cef.Initialize()
browser = cef.CreateBrowserSync(url="https://stackoverflow.com/")
browser.SetClientHandler(LoadHandler())
errorrep.mybrowser = browser
cef.MessageLoop()
del browser
cef.Shutdown()
class LoadHandler(object):
def OnLoadingStateChange(self, browser, is_loading, **_):
if not is_loading:
Thread(target=test).start()
def test():
print("Page loading is complete!")
for i in range(5):
print('scrolling')
# test 1
errorrep.mybrowser.ExecuteJavascript(jsCode="""scrollBy(0,25)""")
# test 2
# errorrep.mybrowser.SendMouseWheelEvent(0,0,0,-120, cef.EVENTFLAG_NONE)
time.sleep(1)
print('opening new page, clicking on the logo link')
errorrep.mybrowser.ExecuteJavascript(jsCode="""document.getElementsByClassName('s-topbar--logo js-gps-track')[0].click();""")
if __name__ == '__main__':
main()
I am using selenium to scrape some data.
This is my code, simplified:
def get_usrs():
#DO SOMETHING
def scroll_down():
#SCROLL UNTIL ARRIVES TO THE BOTTOM OF THE PAGE
#CONTINUE WITH GET_USRS()
The problem is that when the code gets to scroll_down() it doesn't wait until it finishes but continues with get_usrs() and obviously encounters an error.
How can I solve this? Thanks in advance!
So, my code was running with:
try:
get_usrs()
except Exception as e:
print(e)
Now it's running with:
if __name__ == '__main__':
get_usrs()
Works fine.
I am working with some proprietary business software written in DB/C, a short-lived variant of COBOL over 20 years ago with no access to source code or useful documentation of any kind. I've been trying to automate some of our processes with python, and have written a handler object that can pass commands and send various key codes using pyautogui but I have reached a barrier where sometimes I need to rely on the output of the previous routine to decide when/whether to trigger the next. The software GUI runs in a console window, similar to ncurses.
How can I copy the entire contents of my console window to my clipboard? If there is a way to copy it directly to a local python variable that would be ideal; Once I have the screen text I can just match the part I need with a regex.
Here is my handler so far just to give you an idea:
import pyautogui
import time
import subprocess
class ECISession:
def __init__(self, username, password):
self.username = username
self.password = password
self.openECI()
self.login(username, password)
def openECI(self):
# Open ECI as a subprocess
subprocess.Popen("F:\\ECI\\hp4\\test\\s.bat")
def login(self, username, password):
# Login to ECI Session with username and password
time.sleep(15)
pyautogui.write(username, interval=0.1)
pyautogui.press('enter')
pyautogui.write(password, interval=0.1)
pyautogui.press('enter')
pyautogui.write('Y') # Make sure it ignores duplicate login
#staticmethod
def send(text='', supressEnter=False):
# Send passed text to console and press enter unless specified to supress
if text != '':
pyautogui.write(text, interval=0.1)
if supressEnter:
pass
else:
pyautogui.press('enter')
time.sleep(1)
#staticmethod
def sendF3(n=1):
# Send F3 save key 1 time by default, n times if needed
while n != 0:
pyautogui.press('F3')
n -= 1
#staticmethod
def sendF4(n=1):
# Send F4 search key 1 time by default, n times if needed
while n != 0:
pyautogui.press('F4')
n -= 1
#staticmethod
def readscreen():
# return entire console window text
pass
The readscreen() method is what I need to figure out. I just want to return the console content. I would just use the mouse to highlight the entire thing and press enter, but I have no way to make sure the window starts in the same place every time; It can't be maximized or it will crash since it expects an 80 column display with a specific font size.
FYI, the software in question is HealthPac by Eldorado Computing Incorporated. If any of you have used it you know the struggle. I would post some screenshots but it may be a HIPPA violation or something.
So bassicaly the user will press the picture_pin buton first, then this calls the picture_taking() function which then it should stop and wait for either (Accept_Pin or Decline_Pin) buttons to be pressed, it should not let the user to continue unless a selection is made. so when the user makes his/her selection then it go back and wait for the picture_pin button. at this stage the Accept_Pin and Decline_Pin should have no affect at all.
I have a python program that waits for a button press from the user then it runs a function to do its thing. what I would like to accomplish is, in that function I would like to also wait for another button press.
(Main.py)
----etc
## PICTURE FUNCTION ##
def picture_taking():
.....etc
returnvalue = subprocess.check_output("sudo ./" + config.layout + ".sh", shell=True)
GPIO.wait_for_edge(Accept_pin, GPIO.FALLING)
GPIO.wait_for_edge(Decline_Pin, GPIO.FALLING)
pad1alreadyPressed = False
pad4alreadyPressed = False
while True:
pad1pressed = not GPIO.input(Accept_pin)
pad4pressed = not GPIO.input(Decline_Pin)
if pad1pressed and not pad1alreadyPressed:
print "Accepted photo:" + str(returnvalue)
pad1alreadyPressed = pad1pressed
if pad4pressed and not pad4alreadyPressed:
print "Declined photo:" + str(returnvalue)
pad4alreadyPressed = pad4pressed
(This here is my Main Program)
#Main section
while True:
time.sleep(0.2)
#camera.hflip = false
camera.shutter_speed = 2000000000
camera.exposure_mode = 'off'
#camera.iso = 1000
camera.preview_fullscreen = True
camera.preview_alpha = 150
camera.start_preview()
GPIO.wait_for_edge(picture_pin, GPIO.FALLING)
picture_taking()
So in the picture_taking() function I would like to ask the user if they accept this picture or not
if they press button (GPIO 19) then they accept or (GPIO 6) as Decline
after they do there selection the program should go back and wait for the main button to select below. and these two buttons should only be selectable inside the function.
I tried this in the Picture_taking() function
when I make the selection it only accepts the "Decline_pin" button, but after I press the "Decline button" then it reads "Accept button".
The other issue is that it does not go back and wait for the Main button "picture_pin" to be pressed. it seems to be stuck here and not exiting.
I am not sure if this is something to do with Indent stuff in Python.
Thank you.
(This should be a comment, not an answer but I don't have reputation 50 yet).
Is this your actual code? I can't understand how it ever returns from the while True: clause in picture_taking(). I'd think you'd need to have something like
while (!(pad1alreadyPressed or pad4alreadyPressed)):
username = "robertredrain#gmail.com"
password = ""
tomailid = "robertredrain#yahoo.com"
emailsubject = "robertredrain#yahoo.com"
mailbody = "Great! you sent email:-)" + "\n" + "Regards," + "\n" + "Robert"
class send_email(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
self.baseUrl = "http://mail.google.com/intl/en/mail/help/about.html"
def tearDown(self):
self.driver.close();
def testLoginEmail(self):
self.driver.get(self.baseUrl)
self.driver.maximize_window()
self.driver.find_element_by_id("gmail-sign-in").click()
self.driver.find_element_by_id("Email").clear()
self.driver.find_element_by_id("Email").send_keys(username)
self.driver.find_element_by_id("next").click()
time.sleep(5)
self.driver.find_element_by_id("Passwd").clear()
self.driver.find_element_by_id("Passwd").send_keys(password)
self.driver.find_element_by_id("signIn").click()
#Verify login
if "Gmail" in self.driver.title:
print("Logged in sucessfully !!!" + self.driver.title)
else:
print("Unable to loggin :-( " + self.driver.title)
time.sleep(5)
def testComposeEmail(self):
self.driver.find_element_by_xpath("//div[text()='COMPOSE']").click()
time.sleep(5)
self.driver.find_element_by_class_name("vO").send_keys(tomailid)
self.driver.find_element_by_class_name("aoT").send_keys(emailsubject)
self.driver.find_element_by_class_name("Am").clear()
self.driver.find_element_by_class_name("Am").send_keys(mailbody)
self.driver.find_element_by_xpath("//div[text()='Send']").click()
if __name__ == '__main__':
unittest.main()
I am running this send gmail test by Python Unittest with Selenium. The process is after running on SetUp, it runs the 1st function testLoginEmail, which can successfully log in to my gmail account. Then I want to continue to run the 2nd function testComposeEmail, which should be run after the 1st function, because it needs to click the “Compose” button. But it cannot be run.
Could someone help revise the codes that how to run the 2nd function? Thanks a lot!
Note: I haven't tried your code, however there may be two issues.
Issue 1: I believe the unittest functions (other than setUp and tearDown) are run in alphabetical order, not necessarily the order they are in. testComposeEmail would run before testLoginEmail. Should be easy enough to test with print statements. This could be fixed with a judicious rename, e.g. test_1_LoginEmail and test_2_ComposeEmail.
HOWEVER
Issue 2: setUp and tearDown run before and after EACH test, not the whole suite of tests, so fixing Issue 1 will probably not help. I gather the tests should be written to be completely independent of each other.
You could combine the two test into just one monolithic test and see if that works.