I'm sorry if this question has already been answered, but I couldn't find anything on here (except this one which hasn't been answered: link and one that doesn't quite answer the question i'm asking link
I'm creating a button with ipywidgets, but the script doesn't wait for the button to be clicked. Here's a sample of the code/what I'm trying to achieve:
button = widgets.Button(description = "Click")
output = widgets.Output()
display(button, output)
def on_button_clicked(b):
with output:
print("button clicked")
button.on_click(on_button_clicked)
print("Python is ignoring you")
If I run this, I'll just get "Python is ignoring you" before I click the button. I want it to display the button, wait for the person to click it, and only then execute the rest ("Python is ignoring you").
Does anyone have an idea of how I can make python wait for the button to be clicked?
Would appreciate any help! Thanks
I never used the ipywidgets, but the problem is on the last line
you're telling python to print "Python is ignoring you" and python is doing it.
It will not wait for the user to click the button,
because the print statement is out the function "on_button_clicked".(or any)
So just Put it in the function. (That print Statement)
Related
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 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 would appreciate some thoughts on a problem at hand that I've been trying to solve for 1-2 days.
I am running a Python script with Selenium 2.53.6 on FireFox 49.0.1. The script is supposed to click a series of document-download links on a page (I have set the browser to automatically download these file types instead of opening them). Upon clicking, one of the following two events may unfold:
A pop-up window appears. A button on the pop-up window needs to be clicked to close it before the document is downloaded.
A blank pop-up appears momentarily before it disappears on its own when the document download begins.
Here's an excerpt of the script that is written to handle the events above:
file_link = tr.find_element_by_xpath('td[5]/a')
file_link.click()
time.sleep(7) # Allows the blank pop-up to disappear automatically under Event2
agree_button = None
# Checks for the pop-up window
try:
print "Step 1"
driver.switch_to.window(driver.window_handles[1])
print "Step 2" # SCRIPT STOPS RUNNING HERE
agree_button = driver.find_element_by_xpath('//input[#value="Agree and proceed"]')
print "Popup found"
except:
driver.switch_to.window(driver.window_handles[0])
# Clicks the button if the pop-up window is found
if agree_button is not None:
agree_button.click()
print "Button clicked"
The trouble surfaces when there's high latency in the network for Event 2. Under normal circumstances, the blank pop-up disappears almost instantaneously and the download begins immediately after. However, if the network is slow, the blank pop-up may persist beyond the allocated 7 seconds and that resulted in the script running into "Step 2" before the pop-up window disappears.
Strangely, at this point the script doesn't continue on to look for the agree_button. If it does, then that would have triggered the exception and I would be able to revert back to the original window to resume the steps. The script just stalls and does nothing it seems.
Thanks in advance for your time guys!
You need to keep on waiting until the pop-up disappears. One way you might do this is making below changes in your code:
file_link = tr.find_element_by_xpath('td[5]/a')
file_link.click()
time.sleep(7) # Allows the blank pop-up to disappear automatically under Event2
agree_button = None
# Checks for the pop-up window
try:
print "Step 1"
driver.switch_to.window(driver.window_handles[1])
print "Step 2" # SCRIPT STOPS RUNNING HERE
while True:
agree_button = driver.find_element_by_xpath('//input[#value="Agree and proceed"]')
if agree_button is not None:
break
else:
sleep(7)
print "Popup found"
except:
driver.switch_to.window(driver.window_handles[0])
# Clicks the button if the pop-up window is found
if agree_button is not None:
agree_button.click()
print "Button clicked"
Here's the code I'm using on Skulpt:
print('Intro text')
user_input = input('Prompt the user: ')
print(user_input)
The first thing that happens is an empty dialog box pops up, i.e. without the prompt. Only once something is entered in the dialog box does everything print to the output window:
Dialog box with empty text output window
Does anyone have any ideas?
(Right now, I'm using a workaround using time.sleep() before each input() -- ugh)
I have a wxPython script, which executes a process after clicking the button and display the process output in a wx.StaticText.
The problem is when I want to re-execute the process , and so I click on button and the old result is displayed (output of the first process); this old result is still displayed on the window, while I have added an instruction that normally will hide it:
Here is lines of my code:
def OnButton(self, e):
if self.res=="udpscan":
self.resultat1.SetLabel("")
ipad=self.ipadd.GetValue()
fromm=self.fr.GetValue()
too=self.to.GetValue()
ifc=self.intf.GetValue()
if len(ipad) <1 or len(too) < 1 or len(fromm) <1 or len(ifc) < 1:
wx.MessageBox('Please enter missing values','error',wx.OK)
else:
sp=subprocess.Popen(['python','udp_portscan.py',ifc,ipad,fromm,too],stdout=subprocess.PIPE)
text=sp.stdout.readlines()
text="".join(text)
self.resultat1.SetLabel(text)
I have tried to add other intructions to hide it but same problem.
Can you help me please. Thank you
sp seems to store all the previous output in sp.stdout.
There might be a way to clear it using .kill():
sp=subprocess.Popen(['python','udp_portscan.py',ifc,ipad,fromm,too],stdout=subprocess.PIPE)
text=sp.stdout.readlines()
sp.kill()