before, i'm new for this AutoIT, i'm not familiar with this, just google and need to complete my task, if any mistake of my AtotoIt please correct it
scope:
during the Xml Download from IE(version 9) it will open the "Do you want to open or save dialog" so i want to click the save button to save that xml file in default temp folder
my autoIT code(reference from http://qtp-help.blogspot.in/2009/07/selenium-handle-dialogs.html#handle_save_dialog)
AutoItSetOption("WinTitleMatchMode","2") ; set the select mode to select using substring
if $CmdLine[0] < 2 then
; Arguments are not enough
msgbox(0,"Error","Supply all the arguments, Dialog title,Run/Save/Cancel and Path to save(optional)")
Exit
EndIf
; wait Until dialog box appears
WinWait($CmdLine[1]) ; match the window with substring
$title = WinGetTitle($CmdLine[1]) ; retrives whole window title
WinActivate($title)
If (StringCompare($CmdLine[2],"Open",0) = 0) Then
WinActivate($title)
ControlClick($title,"","Button1")
EndIf
If (StringCompare($CmdLine[2],"Save",0) = 0) Then
WinWaitActive($title)
ControlClick($title,"","Button2")
; Wait for the new dialogbox to open
EndIf
If (StringCompare($CmdLine[2],"Cancel",0) = 0) Then
WinWaitActive($title)
ControlClick($title,"","Button3")
EndIf
My java code
WebElement downloadLink = driver.findElement(By
.xpath("(//img[#alt='Download'])[3]"));
downloadLink.click();
Thread.sleep(4000);
dialog = new String[] {
"C:\\Users\\Prabakar\\Desktop\\Save_Dialog_IE.exe", "Save" };
Runtime.getRuntime().exec(dialog);
Please help to solve
Take a look at other ways to download the file without using AutoIT.
How to make browser closed after completing download?
#include <_XMLDomWrapper.au3>
#include <File.au3>
Global $oXML = ObjCreate("Microsoft.XMLHTTP")
$oXML.Open("GET", "YOUR URL LIKE: http://www.google.com", 0)
$oXML.Send
Global $sFile = _TempFile(#TempDir, '~', '.xml')
FileWrite($sFile, $oXML.responseText)
Would this work for you? The XMLDomWrapper.au3 can you get from HERE
Source
Related
I have a use case where I want to read the version of the published extension on edge store.
The link of any published extension is as follows -> https://microsoftedge.microsoft.com/addons/detail/incognito-adblocker/efpgcmfgkpmogadebodiegjleafcmdcb
Now Here the problem I am facing is that the span where the version is location. ( Span ID is "versionLabel" ), has a parent div called "root". Now if we inspect it and check we can see all the children divs of this "root" div. But if we see the source of this page ( Ctrl + U ). This div always shows up empty with no details.
<div id="root" style="min-height: 100vh"></div>
I am using Jsoup to parse this page and get this details but because this div "root" is empty. I can not able to read this "verisonLabel" details. Is there any way to do this ?
Please refer the ways I have already tried but none worked.
1.
String URL = "https://microsoftedge.microsoft.com/addons/detail/incognito-adblocker/efpgcmfgkpmogadebodiegjleafcmdcb";
Document doc = Jsoup.connect(URL).get();
Element version = doc.getElementById("versionLabel");
Document demo = Jsoup.parse(URL);
Element newHere = demo.getElementById("versionLabel");
WebDriver driver = new ChromeDriver();
driver.get(URL);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
WebElement e = driver.findElement(By.xpath("//*[text()='Get started free']"));
System.out.println(e);
String webpage = "https://microsoftedge.microsoft.com/addons/detail/incognito-adblocker/efpgcmfgkpmogadebodiegjleafcmdcb";
URL url = new URL(webpage);
BufferedReader readr =
new BufferedReader(new InputStreamReader(url.openStream()));
// Enter filename in which you want to download
BufferedWriter writer =
new BufferedWriter(new FileWriter("Download.html"));
// read each line from stream till end
String line;
while ((line = readr.readLine()) != null) {
writer.write(line);
}
readr.close();
writer.close();
In each of this ways, because the "root" div itself is empty, I am not able to read the "versionLabel" span.
Can someeone suggest some way here ?
This will get the version from the 'versionLabel':
driver.find_element(By.XPATH, "(//span[#id='versionLabel'])[2]").text
I'm trying to enter text into a field (the subject field in the image) in a section using Selenium .
I've tried locating by Xpath , ID and a few others but it looks like maybe I need to switch context to the section. I've tried the following, errors are in comments after lines.
from selenium.webdriver import Firefox
from selenium.webdriver.firefox.options import Options
opts = Options()
browser = Firefox(options=opts)
browser.get('https://www.linkedin.com/feed/')
sign_in = '/html/body/div[1]/main/p/a'
browser.find_element_by_xpath(sign_in).click()
email = '//*[#id="username"]'
browser.find_element_by_xpath(email).send_keys(my_email)
pword = '//*[#id="password"]'
browser.find_element_by_xpath(pword).send_keys(my_pword)
signin = '/html/body/div/main/div[2]/div[1]/form/div[3]/button'
browser.find_element_by_xpath(signin).click()
search = '/html/body/div[8]/header/div[2]/div/div/div[1]/div[2]/input'
name = 'John McCain'
browser.find_element_by_xpath(search).send_keys(name+"\n")#click()
#click on first result
first_result = '/html/body/div[8]/div[3]/div/div[1]/div/div[1]/main/div/div/div[1]/div/div/div/div[2]/div[1]/div[1]/span/div/span[1]/span/a/span/span[1]'
browser.find_element_by_xpath(first_result).click()
#hit message button
msg_btn = '/html/body/div[8]/div[3]/div/div/div/div/div[2]/div/div/main/div/div[1]/section/div[2]/div[1]/div[2]/div/div/div[2]/a'
browser.find_element_by_xpath(msg_btn).click()
sleep(10)
## find subject box in section
section_class = '/html/body/div[3]/section'
browser.find_element_by_xpath(section_class) # no such element
browser.switch_to().frame('/html/body/div[3]/section') # no such frame
subject = '//*[#id="compose-form-subject-ember156"]'
browser.find_element_by_xpath(subject).click() # no such element
compose_class = 'compose-form__subject-field'
browser.find_element_by_class_name(compose_class) # no such class
id = 'compose-form-subject-ember156'
browser.find_element_by_id(id) # no such element
css_selector= 'compose-form-subject-ember156'
browser.find_element_by_css_selector(css_selector) # no such element
wind = '//*[#id="artdeco-hoverable-outlet__message-overlay"]
browser.find_element_by_xpath(wind) #no such element
A figure showing the developer info for the text box in question is attached.
How do I locate the text box and send keys to it? I'm new to selenium but have gotten thru login and basic navigation to this point.
I've put the page source (as seen by the Selenium browser object at this point) here.
The page source (as seen when I click in the browser window and hit 'copy page source') is here .
Despite the window in focus being the one I wanted it seems like the browser object saw things differently . Using
window_after = browser.window_handles[1]
browser.switch_to_window(window_after)
allowed me to find the element using an Xpath.
I'm unable to get tooltip text of an image element on Salesforce(CRM application) page.
There is a help icon beside a field and when the user hovers over the icon a message is displayed , and I want to capture the help text and assert it for verification.
Firstly, I cannot use .getAttribute("title") as there no text in the title attribute; secondly, .getText() is Not working when I give XPath to the image and apply .getText().
Here is the page source code snippet
Could anyone help me with this, please?
Can you tell me why .getText() is not working? Alternately, you can do this:
1. Extract the HTML code
2. Save it as String
3. Split the string to extract the required text
see How to get HTML code of a WebElement in Selenium
OR
//moving to element which triggers this tooltip
Actions action= new Actions(driver);
action.moveToElement(driver.findElement(By.xpath("//td[#class='labelcol']/span[#class='helpButtonOn']"))).build().perform();
//insert wait here
String hovertext=driver.findElement(By.xpath("//td[#class='labelcol']/span[#class='helpButtonOn']/script")).getText();
System.out.println(hovertext);
OR
// javascript executor
WebElement element = driver.findElement(By.xpath("//td[#class='labelcol']/span[#class='helpButtonOn']/script"));
String hovertext = (String)((JavascriptExecutor)driver).executeScript("return arguments[0].innerHTML", element);
System.out.println(hovertext);
Thank you!!!
This thing below worked for me; the message was found within script tag attribute "text content" OR "innerHTML" which was hidden.
Here is the code:
public void helpTextAssert(WebElement pathOfToolTip, String enterFieldName, String enterExpectedHelpText) {
String originalActualText = pathOfToolTip.getAttribute("textContent");
//Used the below boolean variable, since i have got extra text in text content attribute
Boolean containsTextFlag = pathOfToolTip.getAttribute("textContent").contains(enterExpectedHelpText);
if (originalActualText != null && enterExpectedHelpText != null
&& originalActualText.length() >= enterExpectedHelpText.length() && containsTextFlag == true) {
System.out.println("Help Text: " + enterExpectedHelpText + " is available for field " + enterFieldName);
} else {
sAssert.assertEquals(containsTextFlag, true, "Help text Assersion failed for field: " + enterFieldName);
System.out.println("Help Text: " + enterExpectedHelpText + " is NOT available");
}
}
I'm trying to automate the webpage "http://www.quikr.com",when I open this you will get a pop up window first saying "Please Choose Your Location" then after closing it , I can see the main page of quikr.
I tried closing that Popup page by automation ,but not able to do
Tried using xpath
driver.findElement(By.xpath("//*[#id='csclose']/strong")).click();
Tried using className
driver.findElement(By.className("cs-close cs-close-v2")).click();
Tried using id
driver.findElement(By.id("csclose")).click();
Please help me with this
to close multiple popups in webdriver and switch to parent window
String parent = driver.getWindowHandle();
Set<String> pops=driver.getWindowHandles();
{
Iterator<String> it =pops.iterator();
while (it.hasNext()) {
String popupHandle=it.next().toString();
if(!popupHandle.contains(parent))
{
driver.switchTo().window(popupHandle);
System.out.println("Popu Up Title: "+ driver.switchTo().window(popupHandle).getTitle());
driver.close();
The Following Code Works for Me to Handle Pop Up/ Alerts in Selenium Webdriver
Just Copy Paste this Code After the Event which is triggering the Pop up/Alert i.e after clicking on save.
if(driver.switchTo().alert() != null)
{
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
alert.dismiss(); // alert.accept();
}
in your case you try to run this code at starting of the code bcz it will directly close the pop up
Since this is a JavaScript modal, when the page finishes loading the JavaScript code could still be running. The solution is to wait until the button to close the modal be displayed, close it and then follow with your test. Like this:
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30));
wait.Until(ExpectedConditions.ElementIsVisible(By.Id("csclose")));
driver.FindElement(By.Id("csclose")).Click();
Tested myself and works fine.
Hope it helps.
i have tried it in ruby and this one works
see if this can help you in any way :)
require 'selenium-webdriver'
require 'test/unit'
require 'rubygems'
class Tclogin < Test::Unit::TestCase #------------ define a class----------------
def setup
##driver = Selenium::WebDriver.for :firefox
##driver.navigate.to "http://www.quikr.com" #---- call url----
##wait = Selenium::WebDriver::Wait.new(:timeout => 60) # seconds #----define wait------
end
def test_login
##driver.find_element(:css, "strong").click
end
end
you can also use follwing xpath
##driver.find_element(:xpath, "//a[#id='csclose']/strong").click
public void closePopup() throws Exception {
WebDriver driver = new InternetExplorerDriver();
driver.get("http://www.quikr.com/");
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("csclose"))).click();
System.out.println("Successfully closed the start Popup");
}
Try driver.findElement(By.Id("csclose")).click(); I hope that will help
Simple pressing Alt + F4 buttons worked for me, e.g.:
driver.findElement(By.cssSelector("html body div div img")).sendKeys(Keys.chord(Keys.ALT, Keys.F4));
Is there any way to perform a copy and paste using Selenium 2 and the Python bindings?
I've highlighted the element I want to copy and then I perform the following actions
copyActionChain.key_down(Keys.COMMAND).send_keys('C').key_up(Keys.COMMAND)
However, the highlighted text isn't copied.
To do this on a Mac and on PC, you can use these alternate keyboard shortcuts for cut, copy and paste. Note that some of them aren't available on a physical Mac keyboard, but work because of legacy keyboard shortcuts.
Alternate keyboard shortcuts for cut, copy and paste on a Mac
Cut => control+delete, or control+K
Copy => control+insert
Paste => shift+insert, or control+Y
If this doesn't work, use Keys.META instead, which is the official key that replaces the command ⌘ key
source: https://w3c.github.io/uievents/#keyboardevent
Here is a fully functional example:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
browser = webdriver.Safari(executable_path = '/usr/bin/safaridriver')
browser.get("http://www.python.org")
elem = browser.find_element_by_name("q")
elem.clear()
actions = ActionChains(browser)
actions.move_to_element(elem)
actions.click(elem) #select the element where to paste text
actions.key_down(Keys.META)
actions.send_keys('v')
actions.key_up(Keys.META)
actions.perform()
So in Selenium (Ruby), this would be roughly something like this to select the text in an element, and then copy it to the clipboard.
# double click the element to select all it's text
element.double_click
# copy the selected text to the clipboard using CTRL+INSERT
element.send_keys(:control, :insert)
Pretty simple actually:
from selenium.webdriver.common.keys import Keys
elem = find_element_by_name("our_element")
elem.send_keys("bar")
elem.send_keys(Keys.CONTROL, 'a') # highlight all in box
elem.send_keys(Keys.CONTROL, 'c') # copy
elem.send_keys(Keys.CONTROL, 'v') # paste
I imagine this could probably be extended to other commands as well.
Rather than using the actual keyboard shortcut i would make the webdriver get the text. You can do this by finding the inner text of the element.
WebElement element1 = wd.findElement(By.locatorType(locator));
String text = element1.getText();
This way your test project can actually access the text. This is beneficial for logging purposes, or maybe just to make sure the text says what you want it to say.
from here you can manipulate the element's text as one string so you have full control of what you enter into the element that you're pasting into. Now just
element2.clear();
element2.sendKeys(text);
where element2 is the element to paste the text into
elem.send_keys(Keys.SHIFT, Keys.INSERT)
It works FINE on macOS Catalina when you try to paste something.
I cannot try this on OSX at the moment, but it definitely works on FF and Ubuntu:
import os
import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
with open('test.html', 'w') as fp:
fp.write("""\
<html>
<body>
<form>
<input type="text" name="intext" value="ABC">
<br>
<input type="text" name="outtext">
</form>
</body>
</html>
""")
driver = webdriver.Firefox()
driver.get('file:///{}/test.html'.format(os.getcwd()))
element1 = driver.find_element_by_name('intext')
element2 = driver.find_element_by_name('outtext')
time.sleep(1)
element1.send_keys(Keys.CONTROL, 'a')
time.sleep(1)
element1.send_keys(Keys.CONTROL, 'c')
time.sleep(1)
element2.send_keys(Keys.CONTROL, 'v')
The sleep() statements are just there to be able to see the steps, they are of course not necessary for the program to function.
The ActionChain send_key just switches to the selected element and does a send_keys on it.
The solutions involving sending keys do not work in headless mode. This is because the clipboard is a feature of the host OS and that is not available when running headless.
However all is not lost because you can simulate a paste event in JavaScript and run it in the page with execute_script.
const text = 'pasted text';
const dataTransfer = new DataTransfer();
dataTransfer.setData('text', text);
const event = new ClipboardEvent('paste', {
clipboardData: dataTransfer,
bubbles: true
});
const element = document.querySelector('input');
element.dispatchEvent(event)
Solution for both Linux and MacOS (for Chrome driver, not tested on FF)
The answer from #BradParks almost worked for me for MacOS, except for the copy/cut part. So, after some research I came up with a solution that works on both Linux and MacOS (code is in ruby).
It's a bit dirty, as it uses the same input to pre-paste the text, which can have some side-effects. If it was a problem for me, I'd try using different input, possibly creating one with execute_script.
def paste_into_input(input_selector, value)
input = find(input_selector)
# set input value skipping onChange callbacks
execute_script('arguments[0].focus(); arguments[0].value = arguments[1]', input, value)
value.size.times do
# select the text using shift + left arrow
input.send_keys [:shift, :left]
end
execute_script('document.execCommand("copy")') # copy on mac
input.send_keys [:control, 'c'] # copy on linux
input.send_keys [:shift, :insert] # paste on mac and linux
end
If you want to copy a cell text from the table and paste in search box,
Actions Class : For handling keyboard and mouse events selenium provided Actions Class
///
/// This Function is used to double click and select a cell text , then its used ctrl+c
/// then click on search box then ctrl+v also verify
/// </summary>
/// <param name="text"></param>
public void SelectAndCopyPasteCellText(string text)
{
var cellText = driver.FindElement(By.Id("CellTextID"));
if (cellText!= null)
{
Actions action = new Actions(driver);
action.MoveToElement(cellText).DoubleClick().Perform(); // used for Double click and select the text
action = new Actions(driver);
action.KeyDown(Keys.Control);
action.SendKeys("c");
action.KeyUp(Keys.Control);
action.Build().Perform(); // copy is performed
var searchBox = driver.FindElement(By.Id("SearchBoxID"));
searchBox.Click(); // clicked on search box
action = new Actions(driver);
action.KeyDown(Keys.Control);
action.SendKeys("v");
action.KeyUp(Keys.Control);
action.Build().Perform(); // paste is performed
var value = searchBox.GetAttribute("value"); // fetch the value search box
Assert.AreEqual(text, value, "Selection and copy paste is not working");
}
}
KeyDown(): This method simulates a keyboard action when a specific keyboard key needs to press.
KeyUp(): The keyboard key which presses using the KeyDown() method, doesn’t get released automatically, so keyUp() method is used to release the key explicitly.
SendKeys(): This method sends a series of keystrokes to a given web element.
If you are using Serenity Framework then use following snippet:
withAction().moveToElement(yourWebElement.doubleClick().perform();
withAction().keyDown(Keys.CONTROL).sendKeys("a");
withAction().keyUp(Keys.CONTROL);
withAction().build().perform();
withAction().keyDown(Keys.CONTROL).sendKeys("c");
withAction().keyUp(Keys.CONTROL);
withAction().build().perform();
withAction().keyDown(Keys.CONTROL).sendKeys("v");
withAction().keyUp(Keys.CONTROL);
withAction().build().perform();
String value = yourWebElement.getAttribute("value");
System.out.println("Value copied: "+value);
Then send this value wherever you want to send:
destinationWebElement.sendKeys(value);