When I use selenium webdriver.Chrome().close(), does it will switch to the window before? - screen-scraping

here is my code:
chrome = webdriver.Chrome()
chrome.switch_to.window(self.chrome.window_handles[1])
dosth...
chrome.close()
chrome.switch_to.window(self.chrome.window_handles[0])#
I want to know when I use the method 'close', do I need the last code line to switch to the window before?

chrome.close() closed the webdriver object. Take a look at this post.
So,
chrome.close()
chrome.switch_to.window(self.chrome.window_handles[0])
is wrong. As this will close the webdriver. Instead:
chrome.switch_to.window(self.chrome.window_handles[0])
chrome.close()
is correct.

Related

Is there a way to get the thread-id in Selenium Webdriver Sampler for JMeter?

I need to get the id/number of the actual thread in my Webdriver Sampler code.
Is there a way to identify the thread the code is run from?
There is WDS.ctx shorthand which stands for JMeterContext class instance so you should be able to use getThreadNum() function in order to obtain current thread (virtual user) number:
var threadID = WDS.ctx.getThreadNum()
Demo:
More information: The WebDriver Sampler: Your Top 10 Questions Answered
Use threadNum or ThreadGroupName which ever suits your purpose. Please check the below snapshot for using it in webdriver sampler;-
Hope this helps.

Jmeter WebDriverSampler fail with Chromedriver headless

I have some tests with WebDriverSampler in Jmeter that work correctly with chromedriver. It is a selenium script that opens a web page and checks that it contains a series of elements. Everything works right until I've tried with the chromedriver headless option.
In this case I get the exception "Expected condition failed: waiting for presence of element located by: By.xpath: ..." as if that element did not exist yet to be loaded. I do not know what can happen, because if I stop using the headless option, if everything works correctly and find the element that really exists.
This is an example of code used(it works without the headless option):
var wait = new support_ui.WebDriverWait(WDS.browser, 30);
var conditions = org.openqa.selenium.support.ui.ExpectedConditions
WDS.sampleResult.sampleStart();
WDS.sampleResult.getLatency();
WDS.browser.get('http://mi-app/');
try{
wait.until(conditions.presenceOfElementLocated(pkg.By.xpath('/ruta_de elemento_existente')));
WDS.log.info('OK')
}catch(e){
WDS.sampleResult.setSuccessful(false);
WDS.sampleResult.setResponseMessage('Fail');
WDS.log.error(e.message)
}
try{
wait.until(conditions.presenceOfElementLocated(pkg.By.xpath('/ruta_de elemento2_existente')));
WDS.log.info('OK2')
}catch(e){
WDS.sampleResult.setSuccessful(false);
WDS.sampleResult.setResponseMessage('Fail2');
WDS.log.error(e.message)
}
WDS.sampleResult.sampleEnd();
I hope someone can help me with this problem, because I need to use the headless option. Thank you very much for your time.
You can print the page source to jmeter.log file by using the following function:
WDS.log.info(WDS.browser.getPageSource())
Or even save it into a separate file like:
org.apache.commons.io.FileUtils.writeStringToFile(new java.io.File('test.html'), WDS.browser.getPageSource())
Or take screenshot on failure like:
WDS.browser.getScreenshotAs(org.openqa.selenium.OutputType.FILE).renameTo(new java.io.File('test.png'))
Check out The WebDriver Sampler: Your Top 10 Questions Answered article for more information.
Also be aware that if the machine where you run your Selenium tests doesn't have GUI you can still normally launch browsers using i.e. Xvfb on Linux or under Local System account on Windows

How to take full page screen shot in internet explorer using selenium webdrivers

I am not able to take the whole page screen shot using selenium webdriver.I am using internet explorer.
I tried robot function of java using mouse roll button but failed.
Please try the following let me know if it works for you
WebDriver driver = new FirefoxDriver();
driver.get("http://www.somewebsite.com/");
File imgFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(imgFile , new File("c:\\tmp\\test.png"));
if i have misunderstood you que please let me know
If the above answer fails, you can give a try making using of Augemented WebDriver, which can be used with IEDriver on it's latest version, try following code
WebDriver augmentedDriver = new Augmenter().augment(driver);
File screenFile = ((TakesScreenshot) augmentedDriver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenFile.getAbsolutePath(), new File("c:\\tmp\\test.png"));
You can also get screenshot in the form of bytes, by switching the OutputType as required
.getScreenshotAs(OutputType.BYTES)

How to automate Uploading A file using webdriver.

I am trying to automate a file uploading using webdriver, my HTML is
it is of type file.
using firebug i got the id and it is same for textbox and button.
by using this command getWebDriverObj().findElement(By.id("fileupload")).sendKeys("code.txt"); am unable to fetch the result.
does any one faced this type of situation, if so can you please help me.
Thanks
Raghuram.
Autois Windows specific only.
Here is a more robust solution:
For this you will have find the "id" of the actual input box (where the path of the file is provided) and then use the following command:
driver.findElement(By.id("upload")).sendKeys("/path/to/the/file");
driver.findElement(By.id("upload_button")).click();
If you are using WebDriverBackedSelenium you can use:
selenium.type("locator", "/path/to/the/file");
selenium.click("upload_button");
If previous method is not working
You can try next chain.
1. Call File Select Dialog by click button (use webdriver method click() or javascript "document.getElementById('id').click()"
2. And send control to Autoit (or something another) and AutoIt will work with File Select Dialog (type addres to file, click button)
For example:
var Autoit = new AutoItX3();
const string widowTitle = "File Upload";
Autoit.WinWait(widowTitle, "File &name:", 10);
Autoit.ControlSetText(widowTitle, "", "[CLASS:Edit; INSTANCE:1]", pathToFile);
Autoit.ControlClick(widowTitle, "", "[CLASS:Button; INSTANCE:1]");
Autoit.WinWaitClose(widowTitle, "File &name:", 10);
Setup java and AutoIt http://code.google.com/p/autoitx4java/

Internet Explorer 9 RC stops my WinForms WebBrowser control to work in editing mode

Using the IHtmlDocument2.designMode property set to On to switch a WebBrowser control hosted on a Windows Forms form to editing mode suddenly stopped working after installing Microsoft Internet Explorer 9 RC.
Question:
Any chance to fix this?
I already tried to tweak with doctype or with the EmulateIE7 meta tag but without success.
(An example would be this project)
Update 2011-02-21:
As Eric Lawrence suggested, I adjusted the "Zeta" example to set the document text before setting the edit mode.
Unfortunately I did not manage to switch to design mode, either.
Update 2011-02-24:
Parts of the discussion also take place in Eric's blog.
Update 2011-02-26:
What I currently eperience is that the behaviour seems to be different for HTTP URLs and for content that was added via WebBrowser.DocumentText.
First tests seems to prove this assumption.
I'm now going to build a solution around this assumption and post updates and a proof-of-concept here.
Update 2011-02-26 (2):
I've now built a proof-of-concept with a built-in web server which I believe is also working well with IE 9. If anyone would like to download and test whether it is working and give me a short feedback, I can clean up and release the source code for this.
Update 2011-02-26 (3):
No feedback yet, I still updated the HTML Edit Control article and demo over at the Code Project.
Update 2011-03-16:
Since Internet Explorer 9 was released yesterday, we updated our major products to use the idea with the integrated web server as described in the HTML Edit Control article.
After nearly a month of testing, I think it works quite well.
If you do experience any issues in the future with this approach, please post your comments here and I can investigate and fix.
I had a similar problem and got around it by adding the following line to the DocumentCompleted event:
((HTMLBody)_doc.body).contentEditable = "true";
We just need an empty editable control. I did however step through debugger and add value to the control's InnerHtml and it displayed it fine, and I could edit it.
Small update, we were able to get the control editable using this line also:
browserControl.browser.Document.Body.SetAttribute("contentEditable", "true");
This allows us to avoid referencing mshtml, (don't have to include Microsoft.mshtml.dll)
This lets us avoid increasing our installation size by 8 megs.
What's your exact code?
If I set the following code:
private void cbDesign_CheckedChanged(object sender, EventArgs e){
var instance =
Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateGet(
wbView.ActiveXInstance,
null,
#"Document",
new object[0],
null,
null, null );
var objArray1 = new object[] { cbDesign.Checked ? #"On" : #"Off" };
Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateSetComplex(
instance,
null,
#"designMode",
objArray1,
null,
null,
false,
true );
The IE9 Web Browser instance enters designMode without any problems. If you change the "Zeta" example to not set the document text after entering design mode, it also works fine.
Just want to add that I am also unable to enter designmode (using a WebBrowser control in my case). This was not an issue in the beta. Definitely new with the RC.
Another Code Project user suggested to use the following code:
First, add event DocumentCompleted:
private void SetupEvents()
{
webBrowser1.Navigated += webBrowser1_Navigated;
webBrowser1.GotFocus += webBrowser1_GotFocus;
webBrowser1.DocumentCompleted += this.theBrowser_DocumentCompleted;
}
Then write the function:
private void theBrowser_DocumentCompleted(
object sender,
WebBrowserDocumentCompletedEventArgs e)
{
webBrowser1.Document.Write(webBrowser1.DocumentText);
doc.designMode = "On";
}
Although I did not test this, I want to document it here for completeness.
It's fixed if the property is set after the document is loaded
private void DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
IHTMLDocument2 Doc = Document.DomDocument as IHTMLDocument2;
Doc.designMode = #"On";
}
Yesterday, Internet Explorer 9 RTM finally was released.
I did some more tiny adjustments to my control, but basically the idea with the intergrated, small web server seems to work rather well.
So the solution is in this Code Project article:
Zeta HTML Edit Control
A small wrapper class around the Windows Forms 2.0 WebBrowser control
This was the only solution that worked for me.
I hope it is OK to answer my own question and mark my answer as "answered", too?!?
I was also able to get this to work using the following inside the DocumentCompleted event:
IHTMLDocument2 Doc = browserControl.browser.Document.DomDocument as IHTMLDocument2;
if (Doc != null) Doc.designMode = #"On";
Thanks everyone!
I use HTML Editor Control, I solved this problem adding the DocumentComplete event
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
(((sender as WebBrowser).Document.DomDocument as IHTMLDocument2).body as HTMLBody).contentEditable = "true";
}

Resources