**Python Selenium Behave** Alert box automatically closes after going to next step - python

I am in a project in which I am making a modular behavior driven framework for the company I am working right now. In making a modular approach of the step "user accepts alert", when I test it and came an expected alert box, it automatically closes itself and therefore shows this "NoAlertPresentException: Message: No alert is present" exception.
I have done this codes so far:
def acceptalert():
alert = driver.switch_to.alert
alert.accept()
driver.switch_to.parent_frame()
This code snippet works as I have those modules in which I incorporated the closing of alert box. The only problem is just when I try to make this one a standalone module in my framework. I have done research with this one but I really never got my problem answered. I hope there will be one in here who can help me. Thank you very much.

Found the answer. Thank you. I implemented the step "user clicks '' button" where is the value of the button being matched with a series of xpath and if the xpath returns zero match, then it fetches the available iframes and loops inside each one. When the xpath still returned zero matches, then it switches back to the main frame with this peace of code:
driver.switch_to.parent_frame()
The side effect with this one is it will dismiss the alert boxes. My problem is solved. Thanks everyone.

Related

Selenium Python not finding the element

I'm trying to click on some element but it's not working:
driver.find_element_by_xpath("//span[text()='ENG']")
When I add:
driver.maximize_window()
before click action, it works, other codes are not working again.
I had similar problem
When I was looking for an element, it was not yet available in the code.
Fixed by adding
driver.implicitly_wait(30) ## 30 is the time he will wait
before searching for the element.
This line makes the code wait until the entire page is loaded before looking for an element.
I'm trying to click on some element via driver.find_element_by_xpath("//span[text()='ENG']"), but it's not working,
You need to post logs or be more specific. Are you getting an error on the call to find_element_by_xpath(), or when you call click as you mention below?
when I add driver.maximize_window() before click action, it works,
other codes are not working again, please advise which can be the
reason
The relevant code needs to be provided. I believe you're saying that when you call maximize_window() before you locate the element, it works, but if you don't call maximize window, it fails. This could be for a variety of reasons, but it sounds Javascript related. A similar question like this this could help. If maximize window doesn't actually help the issue, I would look into implicit waits or WebDriverWaits.

Python Selenium - Text dissapeared when using javascript faster input

Hope you are doing well.
The default sendkey method of selenium is somehow slow and I learnt from here that I could use "driver.execute_script" to make faster input.
For most of the sites, ""driver.execute_script" works perfectly but recently I found that for some sites, "driver.execute_script" would input the text but if I press Enter or click anywhere afterward, the text will disspeared.
Below is sample of my code:
driver.get("https://www.apple.com/hk/en")
driver.find_element(By.LINK_TEXT, "Shopping Bag").click()
time.sleep(0.5)
driver.find_element(By.LINK_TEXT, "Sign in").click()
time.sleep(0.5)
driver.execute_script('document.getElementById("recon-0-0").value="abc#abc.com"')
Does anybody knows whether it is restriction of the website or problem of my code?
Thank you for your help.
I looked into this and essentially it is site-side. Seems like rather than an onValueChanged() they are using something like onInput(). Since changing the value directly is not an input action the attribute updates are not triggered (including the actual value). These include:
.class=" form-textbox-input form-textbox-entered", .aria-describedby=" signin-info-id", but most importantly--.aria-invalid="false".
So, in short, changing the value directly makes it fail validation.
.send_keys() does work as expected

Python - Selenium can't handle alert

I'm trying to automate a procedure on a really old IE-only webpage and, at one point, it raises an alert.
I can't inspect it using IE (or don't know how) but there's only an "accept" button (actually an image) and the alert text can't be copied (not sure why).
I'm using selenium with the IE drivers and i can't get past this alert.
Selenium IS detecting the alert, but when i check its contents i get nothing.
I've tried accepting the alert with
alert_obj = self.br.switch_to.alert
alert_obj.accept()
and also
.dismiss();
.send_key(Keys.ENTER)
and some other things. Am i missing something?
photo of alert:
alerts are generic dialog boxes that include a text and ok button. If your alert has an image as button, then it is not an alert, but something else. I don't know what it is, but not an alert.
This is an alert:
If this popup is an alert, you can handle it while initializing driver itself. Below is C# Code for that:
InternetExplorerOptions options = new InternetExplorerOptions
{
UnhandledPromptBehavior = UnhandledPromptBehavior.Accept,
};
driver = new InternetExplorerDriver(options);
Above code should handle alert. if not, try adding this code before creating driver instance.
options.AddAdditionalCapability("browserstack.ie.enablePopups", "accept");
This question is a possible duplicate of:
How to close yet another chrome popup using python selenium
To moderators: I tried to flag this question as Duplicate, but then, when I typed "How to close yet another chrome popup using python selenium" into the search bar it found no results.
I somehow managed to do it.
I tried everything and everything was buggy. I even had to use this weird loop because just using a time.sleep() call was bugging things up. I really don't know what happened. Sometimes when entering the page the pop-up handle would appear and sometimes not. Sometimes in the wrong place. Sometimes it wouldn't close properly. I tried a pile of different ways and this one seems to work:
Here's what i did:
#Saves ID from original window
janelaOriginal = self.br.current_window_handle
#Go to the website
self.br.get(url)
#waits 2.5 seconds for the pop-up (time.sleep bugs)
i = 0
while(i < 25):
i += 1
time.sleep(0.1)
#is pop-up open?:
if(len(self.br.window_handles)>1):
#handle sometimes appears in the wrong place so this is necessary:
if(janelaOriginal==self.br.window_handles[0]):
self.br.switch_to_window(self.br.window_handles[1])
else:
self.br.switch_to_window(self.br.window_handles[0])
#close the pop-up and go back to the original window
self.br.close()
self.br.switch_to_window(janelaOriginal)
#do stuff
return
#do other stuff

How can I avoid inconsistent behavior with Selenium StaleElementReferenceException (Python)?

I'm working on a bit of automation that basically opens YouTube, plays a particular video, then opens the "Stats for Nerds" dialog and grabs the info from it. This was working yesterday. Today, I added lines to set the video to 1080p, then go into full screen, and now it fails to work.
The following line works:
driver.find_element_by_id("movie_player").click()
While this set fails, throwing a StaleElementReferenceException:
element = driver.find_element_by_id("movie_player")
actions.move_to_element(element)
actions.context_click(element)
actions.perform()
Nothing I have done can avoid this. I've tried putting it in a try block, with and without some waits thrown in. Somehow the element is going stale in the very short time between finding and setting the element, and performing the context_click action.
Is there any way of getting around this?
Edit: I'll keep checking back in to see if someone knows a better way to do this, but for now, in the interest of expediency, I've just kludged it by using pymouse to actually take control of the mouse and right click.
I suspect the DOM changes if you mouse over the button. To workaround it, "refind" the element:
element = driver.find_element_by_id("movie_player")
actions.move_to_element(element).perform()
element = driver.find_element_by_id("movie_player")
actions.context_click(element).perform()

How can I program a macro that will do the clicking for me in a web game?

I'm currently playing Mr. Mine and I'm lazy to click 'sell' every 1~2 minutes.
I could use a mouse macro program that I can make the computer to do the clicking for me but this sounds like an inelegant method.
I was thinking about some way I could make a code that will hack into the web browser with the web game on and somehow send some kind of 'request' to the server that will sell the minerals.
I mean, after all, clicking it by hand eventually will send some request to the server so why not do this sending through a preprogrammed code?
I know my question is broad, so let me ask a few questions that will give me a lead to start on my project.
What to I need to learn to understand the 'sending request' part?
Is there anyone or any script that has already done what I want to do?
I'd like to take a look at the source code. (it's okay even if its not Mr.Mine. any other web game would also be of help)
Also, I'm currently interested in python so if there's any example in python, I'd be really thankful.
update: "I've solved the problem"
I'm just writing how I solved the problem just in case some other folk who just started Mr.Mine faces the same laziness that I did.
As it turns out, Mr.Mine doesn't actually exchange packets with its server. It only uses internet connection for initial loading of images and all that.(I think it is..)
If you right click on the Mr.Mine web page and view the html code of it, you'll find that its full of javascripts.
After roughly reading through these javascripts, my theory that this game doesn't rely much on packet data became more persuasive.
Anyway that's why I approached my problem at a javascript perspective and I finally got a solution
What you need to do is utilize chrome's developer tools.(I'm a chrome user)
You can access to this tool also simply by: from the mr.mine web page, right click anywhere -> click the very last button. Then you'll see some panel popping up at the bottom of the screen.
this tool enables you to fiddle with the html code or javascript in it.
I'm not good at this either since this is my first time actually using it for a practical purpose.
I just managed to scrape enough knowledge about this by googling to satisfy my needs.
In this new panel, at the top menubar, there's the 'Console' tab on the very right.
Click this and you'll see a command console.
This is where you can execute java commands within the javascript of the webpage.
Well from here, its strictly 'Mr.Mine' related.
From my previous rough reading of the javascript, I found that the sell buttons have been given the ID such as 'SB2', 'SB3', 'SB4', and so on.
So what I did was just type
setInterval(document.getElementById("SB2").onclick, 300);
at the command line and pressed enter.
this command will automatically press the SB2 button(which corresponds to 'Coal') every 0.3 seconds.
*Caution: you must have the 'selling' page opened when this code is executed. I found out that if the 'sell' page is not opened, the code doesn't work.
*Caution2: another funny thing is, even within the 'sell' page, if you transfer to the 'sell isotope' page, it will automatically sell Uranium 238. That's because the SB2 button corresponds to Uranium 238 in 'sell isotope' tab. So be careful!
*Caution3: if you do this, an error popup will constantly come up. I just enabled the 'never show this popup' checkbox and after that it just worked fine. But one side effect: the usual popup that came up after pressing the 'save' button no longer appeared... but its worth the sacrifice isn't it?
anyway, if you want to automatically sell other ores, all you have to do is type similar codes like:
setInterval(document.getElementById("SB3").onclick, 300);
setInterval(document.getElementById("SB4").onclick, 300);
... etc.
see that just changing the number after "SB" corresponds to the next ore(isotope) in the list.
Well, thanks for reading this much, and I hope other Mr.Mine users can be creative and do more through this technique.
You could use a packet capturing tool such as wireshark. With that figure out the format and data that the game sends to the server.
Once your know the structure you could write your script to intercept your game traffic, add the needed parameters and send requests on a timed basis. (This is all assuming it does encrypt its network traffic, in which case this may be a bit more difficult)
You may find some additional information with this search.
perhaps you can use http://www.sikuli.org/. i have successfully used this to do a fairly complicated automation routine for eve online.

Categories