Below is my code :
import time
import pyautogui
location = pyautogui.locateOnScreen('ok.png')
pyautogui.click(location)
Now I don't know when the "OK" image appears. So I want to loop the code to search for the image until it is found. Otherwise it is terminating immediately before the image appears.
Once found break the loop and click that image.
How do I do I do that?
And time.sleep() dosent work because the image can appear anytime.
I have done something similar,
Using the autoit module to find the window title and button name
import autoit,time
while True:
try:
autoit.control_click("[TITLE:MTMS Update; CLASS:#32770]", "Button1")
print("Clicked OK")
except:
time.sleep(30)
pass
Related
I want to make a program that automatically cleans my pc with CCleaner, by searching for specific images on the screen, moving the mouse to that position, and clicking on it, and waiting 0,5 secs if it doesn't find the image. the first loop, which opens CCleaner works as intended, but what it seems like it skips the second loop, and then tries doing the one after that. When I try to put a breakpoint at the second try, it appears that it successfully moves the mouse to where it needs to go, but it doesn't click() it, and then break and tries to do the next loop. sleep() after every line, but it didn't fix it so it shouldn't be timing issue.
Why does it only move the mouse where it needs to go, when I'm debugging, and why isn't it click()ing?
import pyautogui
import time
import PIL
import picsData
pics = picsData.__dict__.get("pics")
while True:
try:
point = pyautogui.center(pyautogui.locateOnScreen(pics.get("ccleaner")))
pyautogui.moveTo(point)
pyautogui.click(clicks=2)
break
except:
time.sleep(0.5)
time.sleep(0.5)
while True:
try:
point = pyautogui.center(pyautogui.locateOnScreen(pics.get("health")))
pyautogui.moveTo(point)
pyautogui.click(clicks=2)
break
except:
time.sleep(0.5)
while True:
try:
point = pyautogui.center(pyautogui.locateOnScreen(pics.get("healthstart")))
pyautogui.moveTo(point)
pyautogui.click()
break
except:
time.sleep(0.5)
When visiting some websites with selenium there are times where the page doesn't load correctly. So I want to write a code that checks if the website loaded correctly by searching for a particular button. If it can't find the button it needs to refresh until it finds the button and if the code does find the button it needs to execute the rest of the code.
So for example: Button not there: >>> refresh >>> (checks again if button is not there) Button not there >>> refresh >>> (checks again if button is not there) Button is there >>> rest of code
The loop that I currently have looks like this but after refreshing the loop doesn't restart and runs the else: function.
So the question is how do I make a loop that restarts the loop after it refreshes.
while not (driver.find_elements(By.CLASS_NAME, "button")):
driver.refresh()
else:
Rest of code
Help would be much appreciated, thanks in advance
You can have an infinite while loop, and an if condition with find_elements, Please note that find_elements does not return any exception, it returns a list of web elements or either 0.
Code:
while True:
try:
if len(driver.find_elements(By.XPATH, "xpath of the button")) >0:
print("Button is present, since find elements list is non empty")
# execute the code, may be click on the button or whatever it is.
#make sure to exit from infinite loop as well
break
else:
driver.refresh()
#may be put some delay here to let button available to click again.
except:
print("There was some problem trying to find the button element, tearing it down")
break
I know I can use time.sleep(), but I need something that would affect whole script.It is automatic test homework and aplication buttons are clicked almost instantly. It is a bit anoying because I cant see if everything is working as supposed(still learning).
import pyautogui
import time
from pywinauto.application import Application
app = Application(backend="uia").start(r"C:\Users\User\Desktop\WPF_RentACar_3maj\WPFRentACar\bin\Debug\WPFRentACar.exe")
pyautogui.FAILSAFE = True
#app.LoginWIndow.print_control_identifiers()
dlg =app.LoginWindow
dlg.MaximizeButton.click()
dlg.MinimizeButton.click()
dlg.MaximizeButton.click()
dlg.Restore.click()
try:
dlg.Edit1.type_keys("123")
dlg.Edit2.type_keys("123")
dlg.LoginButton.click()
dlg.Button1.click()
finally:
print("Cant login with wrong credentials!")
time.sleep(2)
dlg.Edit1.type_keys("'^a{BACKSPACE}")
dlg.Edit2.type_keys("'^a{BACKSPACE}")
dlg.LoginButton1.click()
time.sleep(5)
time.sleep() does stop the whole script. Or are you using threading or python 2? Also can you tell us what you are also trying to automate.
I am trying to get followers with python selenium. But sometimes python clicks by itself.
I want to make an error-free program. I try to I've tried "try catch" constructs but it didn't work. Here is my code:
def getFollowers(self):
try:
self.browser.get(f"https://www.instagram.com/{self.username}")
time.sleep(2)
followers=self.browser.find_element_by_xpath("//*[#id='react-root']/section/main/div/header/section/ul/li[2]/a").click()
time.sleep(2)
dialog=self.browser.find_element_by_xpath("/html/body/div[5]/div/div/div[2]")
followerCount=len(dialog.find_elements_by_tag_name("li"))
print(f"first count:{followerCount}")
action=webdriver.ActionChains(self.browser)
//*******************************************Probly my problem is here****************************************
while True:
dialog.click()
action.key_down(Keys.SPACE).key_up(Keys.SPACE).perform()
time.sleep(3)
newCount=len(dialog.find_elements_by_tag_name("li"))
if followerCount!=newCount or newCount==24:
print(f"New count:{newCount}")
time.sleep(3)
followerCount=newCount
else:
break
//**********************************************************************************************************
followers=dialog.find_elements_by_tag_name("li")
followersList=[]
for user in followers:
link=user.find_element_by_css_selector("a").get_attribute("href")
# print(link)
followersList.append(link)
with open("followers.txt","w",encoding="UTF-8") as file:
for item in followersList:
file.write(item+"\n")
time.sleep(5)
except:
pass
I also have def getfollowing and it works flawlessly. If you want I can show it too. But they are almost same.
EDIT: #RohanShah solved my problem. At the bottom of the page you can see the solution.
Edit: I am new here thats why sometimes my questions could be meanless.But please dont decrease my points. Stackoverflow not gonna accept my questions anymore. Please increase my points.
I've had this exact same problem while scrolling the popups. What happens is your dialog.click(), while attempting to focus your key down on the popup, occasionally clicks a user and loads their profile. Your script then crashes as the popup is no longer on the screen.
After a lot of research into solving this problem, I noticed it only happens with usernames that are long. Regardless, I implemented a simple hack to get around this problem.
First we get the url of what the standard scroll looks like. When opening and scrolling the popup, this is the url we are on.
https://www.instagram.com/some_username/followers/
2.Now I have created a function to hold the code for opening the popup. This will be very useful so trap the necessary code into a function. (I don't have the classnames or xpath's on me so please customize the function for yourself)
def openPopup():
self.browser.get(f"https://www.instagram.com/{self.username}")
global popup # we will need to access this variable outside of the function
popup = driver.find_element_by_class_name('popupClass') #you don't have to use class_name
popup.click()
Now we have to tell our while loop to not scan when Selenium accidentally clicks on a user. We will use our URL from step 1. Please make sure the following if-statement is inserted at the TOP of your loop so if there is a break, it will handle it first before trying to access the popup.
while True:
check_url = self.browser.current_url #returns string with current_url
if check_url != 'https://www.instagram.com/some_username/followers/':
#if this code is executed, this means there has been an accidental click
openPopup() #this will bring back to the page and reopen popup
#the rest of your code
popup.click() # variable from our function
action.key_down(Keys.SPACE).key_up(Keys.SPACE).perform()
time.sleep(3)
newCount=len(dialog.find_elements_by_tag_name("li"))
if followerCount!=newCount or newCount==24:
print(f"New count:{newCount}")
time.sleep(3)
followerCount=newCount
else:
break
check_url = self.browser.current_url #we must recheck the current_url every time the loop runs to see if there has been a misclick
Now, whenever your loop detects the URL is no longer one of the popup, it will automatically call openPopup() which will get you back to the page and back in the popup, and your loop will continue as if nothing happened.
I'm trying to open and close a picture. Open it at the beginning of the loop and close it at the end of the loop. So far I've only managed to open the image, however for the closing I couldn't find the right options.
For opening I'm using
img = os.startfile("image.jpg")
and for closing I've tried
img.close()
I've also tried
os.close("image.jpg")
How does one do this?
Something in that direction:
import subprocess
import os
import signal
import time
image_viewer = "name of the image viewer program"
pid = subprocess.Popen([image_viewer, "image.jpg"]).pid
time.sleep(5)
os.kill(pid, signal.SIGTERM)
You need to know the name of an application used to view the image.
If it's just about displaying an image, you can also use a GUI toolkit like tkinter.