Customize the browser icon when running a Selenium session? - java

I have some Selenium sessions where, if certain events occurs, I spawn a new browser and leave the old one as is so I later on can manually intervene. The problem is that it is hard to distinguish between such a deserted browser session and the one that is currently running.
Ideally I would like to add a badge to the browser icon that is displayed in the application switcher (cmd-tab) and the dock (but other solutions/suggestions are also welcome, like add something to the name of the browser). Is that possible?
Using Java on a Mac. A solution can be platform specific.

You can use below execute_script (This python code use java equalent)
from selenium import webdriver
import time
driver = webdriver.Chrome()
driver.get(
"https://stackoverflow.com/questions/9943771/adding-a-favicon-to-a-static-html-page")
head = driver.find_element_by_tag_name("head")
link = driver.find_element_by_css_selector('link[rel="shortcut icon"]')
driver.execute_script('''var link = document.createElement("link");
link.setAttribute("rel", "icon");
link.setAttribute("type", "image/png");
link.setAttribute("href", "https://i.stack.imgur.com/uOtHF.png?s=64&g=1");
arguments[1].remove();
arguments[0].appendChild(link);
''',head,link)
time.sleep(70000)
you can use link element on head tag to add favicon. THe above code is an exaple where stackoverflow site will showup with my avatar
Output:
You should find the current link the website uses, remove it and replace it with your new link as shown in the code

Related

Login ajio.com by Google/Facebook account using selenium web driver in java

I am new to selenium ad I can't able to login ajio
coding using google or my facebook account i even tries windows handling concept but it is having single window id but new tab appears and i tries using some key concepts like(\t) &(t) also but still i cannot pass my mail id in google account tab not only that no others buttons working on that new page pls clear my doubt.. suggest idea to make it work new tab(which is not allowed to automate)Exception
Note: I'm using java with selenium 3.141.59 & Chrome version 93.0.4577.82
Actually login window is opening in another tab so you need to switch focus to another window. following code is working for me.
Set<String> windowslist = driver.getWindowHandles();
String lastwindow = null;
for(String eachWindow : windowslist){
lastwindow = eachWindow;
}
driver.switchTo().window(lastwindow);
wait.until(ExpectedConditions.visibilityOfElementLocated(emailBox));
driver.findElement(emailBox).sendKeys("jayanthbala1993#gmail.com");

How do I scrape data being a login screen for different login names?

I'm trying to compile the results of my class from my college's results page (exam.msrit.edu).
The USNs for my class are from 1MS16CS001-100
Is there any way that I could go about writing a scraper program to enter different values in the USN box and gather data?
I am quite new to scraping but have decent enough exposure to Python and java
Any advice is much appreciated :)
Not necessarily a scrape, but you can use Selenium Web Driver to browse to the page and input everything for you. Selenium Web Driver can be found here.
Essentially, once it is installed you only need to instantiate the driver and then loop through a list of values inputting them as you go.
from selenium import webdriver
# V sets up browser. If you want to use chrome addtional setup required
browser = webdriver.Firefox()
for i in len(100): #loops to arbitrary amount
browser.get("http://exam.msrit.edu/") #HTTP GET Request to page
elem = browser.find_element_by_id('id') #This is an html id. Could also use name, xpath, etc.
elem.send_keys("your string {}".format(i)) #sends up keys
elem. browser.find_element_by_id('id) #id for search button
elem.click() #clicks that element
The documentation on selenium is pretty good. http://selenium-python.readthedocs.io/navigating.html
This will open a actual browser and will take some time to load so it will not be the quickest way to do it but it will work. You can even take screenshots.

Switching between tabs using webdriver in chrome

Am Opening a page performing some actions on that and i am using this piece of code to open another link in the next tab
String url = "https://qa.logfireapps.com/lgf_700_qa_rf";
String args1 = String.format("window.open('%s', '%s');", url, "new");
((JavascriptExecutor) driver).executeScript(args1);
Then i need to switch between this two tabs.
I used driver.switchTo.window(parentWin);
I also used this code
List windowHandles1 = new ArrayList(driver.getWindowHandles());
driver.switchTo().window(windowHandles1.get(1));
Both of the cases did not work for me,but still the web driver code is running successfully without any errors even its not switching to first window.
I need to switch to the first tab,but all the actions are going on in the first tab but still in UI am seeing the second tab opened,It is not switching to the first tab but my whole webdriver code gets passed.
It is observed that switching problem happens only with this two sites
1) https://qa.logfireapps.com/lgf_700_qa/index/
2) https://qa.logfireapps.com/lgf_700_qa_rf
This was my solution to this using python. sorry no java example
def switch_to_new_window(driver, window):
driver.switch_to_window(driver.window_handles[window])

Bring the Firefox Browser to Front using selenium Java (Mac OSX)

I am using three instances of fire fox driver for automation.I need to bring current active firefox browser into front, Because I am using some robo classes for some opertation. I had tried java script alert for google chrome in mac ( same operation) and its worked fine. In windows used user32 lib. In the case of firefox mac its showing the alert in background but the web page is not come into front.
((JavascriptExecutor)this.webDriver).executeScript("alert('Test')");
this.webDriver.switchTo().alert().accept();
The above code I used for chrome in Mac. Same code is working and showing alert for firefox but the window is not coming to front.
Please suggest if there any other method for doing the same in firefox.
Store the window handle first in a variable, and then use it to go back to the window later on.
//Store the current window handle
String currentWindowHandle = this.webDriver.getWindowHandle();
//run your javascript and alert code
((JavascriptExecutor)this.webDriver).executeScript("alert('Test')");
this.webDriver.switchTo().alert().accept();
//Switch back to to the window using the handle saved earlier
this.webDriver.switchTo().window(currentWindowHandle);
Additionally, you can try to maximise the window after switching to it, which should also activate it.
this.webDriver.manage().window().maximize();
Try switching using the window name:
driver.switchTo().window("windowName");
Alternatively, you can pass a "window handle" to the switchTo().window() method. Knowing this, it’s possible to iterate over every open window like so:
for (String handle : driver.getWindowHandles()) {
driver.switchTo().window(handle);
}
Based on the Selenium documentation: http://docs.seleniumhq.org/docs/03_webdriver.jsp
As described in other topics, you can use
driver.manage().window().setPosition(new Point(-2000, 0));
too.
# notifications for selenium
chrome_options = webdriver.ChromeOptions()
prefs = {"profile.default_content_setting_values.notifications": 2}
chrome_options.add_experimental_option("prefs", prefs)
current_path = os.getcwd() # current working path
chrome_path = os.path.join(current_path, 'chromedriver')
browser = webdriver.Chrome(executable_path=chrome_path, chrome_options=chrome_options)
browser.switch_to.window(browser.current_window_handle)
browser.implicitly_wait(30)
browser.maximize_window()
browser.get("http://facebook.com")
Only thing that worked for me on mac: self.driver.fullscreen_window().

How to deal with file uploading in test automation using selenium or webdriver

I think that everybody who uses Webdriver for test automation must be aware of its great advantages for web development.
But there is a huge issue if file uploading is part of your web flow. It stops being test automation. The security restriction of browsers (invoking file selection) practically makes it impossible to automate tests.
Afaik the only option is to have Webdriver click the file upload button, sleep the thread, have developer/tester manually select the file, and then do the rest of the web flow.
How to deal with this, is there a workaround for it? Because it really can't be done like this. It wouldn't make sense.
This is the only case I know of when browser security restrictions do not apply:
<script language=javascript>
function window.onload(){
document.all.attachment.focus();
var WshShell=new ActiveXObject("WScript.Shell")
WshShell.sendKeys("D:\MyFile.doc")
}
</script>
Webdriver can handle this quite easily in IE and Firefox. Its a simple case of finding the element and typing into it.
driver = webdriver.Firefox()
element = driver.find_element_by_id("fileUpload")
element.send_keys("myfile.txt")
The above example is in Python but you get the idea
Using AWT Robots is one option, if you're using Java, which you are. But it's not a good option, it is not very dependable, and not clean at all. Look here
I use HttpClient and run a few tests outside of Selenium. That's more dependable and cleaner.
See the code below. You'll need more exception handling and conditionals to get it to suit your job.
HttpClient c = new HttpClient();
String url = "http://" + cargoHost + ":" + cargoPort + contextPath + "/j_security_check";
PostMethod post = new PostMethod(url);
post.setParameter("j_username", username);
post.setParameter("j_password", password);
c.executeMethod(post);
url = "http://" + cargoHost + ":" + cargoPort + contextPath + "/myurl.html";
MultipartPostMethod mPost = new MultipartPostMethod(url);
String fileNameWithPath = this.getClass().getClassLoader().getResource(filename).getPath();
File f1 = new File(fileNameWithPath);
mPost.addParameter(elementName, f1);
mPost.addParameter("action", "upload");
mPost.addParameter("ajax", "true");
c.executeMethod(mPost);
mPost.getResponseBodyAsString();
The suggestion of typing into the text box works only if the textbox is enabled.
Quite a few applications force you to go through the file system file browser for obvious reasons.
What do you do then?
I don't think the WebDriver mavens thought of just presenting keys into the KeyBoard buffer (this used to be a "no brainer" in earlier automation days)
===
After several days of little sleep, head banging and hair pulling I was able to get some of the Robot-based solution suggested here (and elsewhere).
The problem i encountered was that the dialog text box that was populated with the correct file path and name could not respond to the KeyPress/Release Events of terminating the file name with VK_ENTER as in:
private final static int Enter = KeyEvent.VK_ENTER;
keyboard.keyPress(Enter);
keyboard.keyRelease(Enter);
What happens is that the file path and file name are typed in correctly but the dialog remains opened - against my constant hoping and praying that the key emulation will terminate it and get processed by the app under testing.
Does anyone know how to get this robot to behave a bit better?
Just thought I'd provide an FYI to author's original post of using ActiveX. Another workaround would be to integrate with desktop GUI automation tools to do the job. For example, google "Selenium AutoIt". For a more cross-platform solution, consider tools like Sikuli over AutoIt.
This of course, is not considering WebDriver's support for uploads on IE & Firefox via SendKeys, or considering for other browsers where that method doesn't work.
After banging my head on this problem for far too many hours, I wanted to share with the community that Firefox 7.0.1 seems to have an issue with the FirefoxDriver sendKeys() implementation noted above (at least I couldn't get it to work on my Windows 7 x64 box), I haven't found a workaround, but updating to Firefox 8.0.1 seems to have fixed the problem. For those of you wondering, it's also possible to use Selenium RC to solve this problem (though you need to account for all of your target operating systems and the native key presses required to interact with their file selection dialogs). Hopefully the issues I had to work around save other people some time, in summary:
https://gist.github.com/1511360
If you have your are using a grid, you could make the folder of the testfiles open for sharing.
This way you could select the upload input field and set its value to \\pc-name\myTestFiles
If you're not, you should go with local files on each system.

Categories