Java - Clicking on an image using HtmlUnit - htmlunit

I'm doing a personal project that involves getting data out of a website, I managed to make it automatically log in and all of that, but i have reached a point where i have to click on an image
img src="data:image/png;base64, {{sc.PhotoLocation}}" style="width: 75px; margin-top:3px;cursor:pointer" class="ng-cloak" ng-click="sc.selectPerson(sc.person_Guid)" title="View Student Record" /
to progress to another menu of that page, after multiple google searches and documentations i decided on using XPath
HtmlImage image = page.<HtmlImage>getFirstByXPath("//img[#src=\'data:image/png;base64, sc.PhotoLocation}}\']");
page = (HtmlPage) image.click();
problem is, i'm getting a NullPointerException out of this, anything i did wrong? Thanks.
Rest Of The Code:
WebClient webClient = new WebClient();
HtmlPage page = webClient.getPage("https://myWebsite");
HtmlInput username = page.getElementByName("Template1$MenuList1$TextBoxUsername");
username.setValueAttribute("myUsername");
HtmlInput password = page.getElementByName("Template1$MenuList1$TextBoxPassword");
password.setValueAttribute("myPassword");
HtmlSubmitInput loginButton = page.getElementByName("Template1$MenuList1$ButtonLogin");
page = loginButton.click();
webClient.waitForBackgroundJavaScript(2000);
if (page.getElementByName("Template1$Control0$ButtonContinue") != null) {
HtmlSubmitInput continueButton = page.getElementByName("Template1$Control0$ButtonContinue");
page = continueButton.click();
webClient.waitForBackgroundJavaScript(2000);
}

Hi #Orestesk Welcome to SO,
Your xpath is not correct.
src attribute of you image is dynamic. src="data:image/png;base64, {{sc.PhotoLocation}}"
Here {{sc.PhotoLocation}} would evaluate to some value. So value of src attribute keeps changing depending on the value of sc.PhotoLocation.
Use some other strategy to select your image instead of relying on src attribute.
OR try this trick.
//img[contains(#src, 'data:image/png;base64')]

Related

Laravel file manager standalone iframe to input

I don't know how can't I find any examples on this, like no one used it before..
I want to open file manager in iframe and on images click to insert image url to input. Their example opens new window...
I am using laravel file manager standalone button to change avatar image but by their docs I can do it like this:
<div class="input-group">
<span class="input-group-btn">
<a id="lfm" data-input="thumbnail" data-preview="holder" class="btn btn-primary">
<i class="fa fa-picture-o"></i> Choose
</a>
</span>
<input id="thumbnail" class="form-control" type="text" name="filepath">
</div>
<img id="holder" style="margin-top:15px;max-height:100px;">
And calling $('#lfm').filemanager('image');
Which works but it opens new window because this is .filemanager()
(function( $ ){
$.fn.filemanager = function(type, options) {
type = type || 'file';
this.on('click', function(e) {
var route_prefix = (options && options.prefix) ? options.prefix : '/laravel-filemanager';
localStorage.setItem('target_input', $(this).data('input'));
localStorage.setItem('target_preview', $(this).data('preview'));
window.open(route_prefix + '?type=' + type, 'FileManager', 'width=900,height=600');
window.SetUrl = function (url, file_path) {
//set the value of the desired input to image url
var target_input = $('#' + localStorage.getItem('target_input'));
target_input.val(file_path).trigger('change');
//set or change the preview image src
var target_preview = $('#' + localStorage.getItem('target_preview'));
target_preview.attr('src', url).trigger('change');
};
return false;
});
}
})(jQuery);
Now changing:
window.open(route_prefix + '?type=' + type, 'FileManager', 'width=900,height=600');
To:
$('iframe').attr('src', route_prefix + '?type=' + type);
Will append filemanager to iframe as I want but when I click on image inside iframe it opens image in new tab as it is setting new url but skipping the script?
I think that I could get image url if it was opening in iframe but it is not...
Do you maybe know how to do this?
Thanks
I found out answer for my needs, not finished one tho but it works as needed:
Open up script.js from vendor/..../js folder and change useFIle function if/else statement where it looks up are you using any editor (cke,mce,etc..) and if not it just opens image in new window.
I remove that option and added this:
// parent.document.getElementById(field_name).value = url;
var target_input = parent.document.getElementById(localStorage.getItem('target_input'));
target_input.value = url;
//set or change the preview image src
var target_preview = parent.document.getElementById(localStorage.getItem('target_preview'));
target_preview.src = url;
From my question you can see jquery-plugin for opening laravel-filemanager into iframe and adding elements to localstorage.
I used that elements from localstorage in iframe to append url in input and display image in holder.
Now I will change this a little bit, since I wan't to leave this script as it is for full manager page on that url. I will just add another field as uri to be able to say this url is opened by iframe and use someOtherFUnction instead of useFile function by default.

How to get captcha img src with Ruby and Mechanize?

I'm trying to write simple crawler, that would be filling 2 input fields. The page has an img element. Through Chrome developer mode I can see that img has src attribute. But after fetching the page the src attribute is gone. How do I get over this?
Code:
require 'mechanize'
agent = Mechanize.new
agent.user_agent_alias = 'Windows Chrome'
page = agent.get('https://ercdmd.ru/?gpay')
form = page.forms.first
form.gpay_abon = '00-0000000000'
captcha = page.at('#img_captcha')
pp captcha
Output:
#(Element:0x15e90ec {
name = "img",
attributes = [ #(Attr:0x15e8c14 { name = "id", value = "img_captcha" })]
})
My idea is to get invoice by a query through Telegram bot. Since there is a captcha I thought that I could read captcha image src with Mechanize to send that image through Telegram. Than, I would input digits that I can see on image and send in back to Mechanize to fill second input field. But now I am stuck.
Is there an other way to get invoice from that source?
I'm looking at that page, the captcha url would be:
captcha_url = "https://ercdmd.ru/captcha.php?time=#{Time.now.to_i}000"
Give that a try and see if it works.

Getting raw text using #Html.ActionLink in Razor / MVC3?

Given the following Html.ActionLink:
#Html.ActionLink(Model.dsResults.Tables[0].Rows[i]["title"].ToString(), "ItemLinkClick",
new { itemListID = #Model.dsResults.Tables[0].Rows[i]["ItemListID"], itemPosNum = i+1 }, ...
Data from the model contains HTML in the title field. However, I am unable to display the HTML encoded values. ie. underlined text shows up with the <u>....</u> around it.
I've tried Html.Raw in the text part of the ActionLink, but no go.
Any suggestions?
If you still want to use a helper to create an action link with raw HTML for the link text then I don't believe you can use Html.ActionLink. However, the answer to this stackoverflow question describes creating a helper which does this.
I would write the link HTML manually though and use the Url.Action helper which creates the URL which Html.ActionLink would have created:
<a href="#Url.Action("ItemLinkClick", new { itemListID = #Model.dsResults.Tables[0].Rows[i]["ItemListID"], itemPosNum = i+1 })">
#Html.Raw(Model.dsResults.Tables[0].Rows[i]["title"].ToString())
</a>
MVCHtmlString.Create should do the trick.
Using the actionlink below you do not need to pass html in the model. Let the css class or inline style determine how the href is decorated.
#Html.ActionLink(Model.dsResults.Tables[0].Rows[i]["title"], "ItemLinkClick", "Controller", new { #class = "underline", style="text-decoration: underline" }, null)
those are the cases that you should take the other path
#{
string title = Model.dsResults.Tables[0].Rows[i]["title"].ToString(),
aHref = String.Format("/ItemLinkClick/itemListID={0}&itemPosNum={1}...",
Model.dsResults.Tables[0].Rows[i]["ItemListID"],
i+1);
}
#Html.Raw(title)
Remember that Razor helpers, help you, but you can still do things in the HTML way.
You could also use this:
<a class='btn btn-link'
href='/Mycontroler/MyAction/" + item.ID + "'
data-ajax='true'
data-ajax-method='Get'
data-ajax-mode='InsertionMode.Replace'
data-ajax-update='#Mymodal'>My Comments</a>

problem rendering image in browser FileContentResult

I want to show an image from database
I have an action
public FileContentResult GetImage(string param)
{
type obj = _someRepository.GetType(param);
if (obj!= null && obj.Image!= null)
{
return File(obj.Image.ToArray(), obj.Image.MimeType);
}
return "some default image";
}
in the view I have
< img src="<%:Url.Action("GetImage","ControllerName",new { param= somevalue })%>" alt="some text"
width="100px" height="100px" />
I also have
(Html.BeginForm("actionname", "controllername", FormMethod.Post, new { enctype = "multipart/form-data" })
set.
The image data is fetched from the database But I can't see the image in the browser,
is there something that I am missing?
Here are the steps I would perform in order to isolate the problem. Start with a simple controller action which returns some hardcoded image somewhere from your harddrive:
public ActionResult GetImage(string param)
{
byte[] image = File.ReadAllBytes(#"c:\work\foo.png");
return File(image, "image/png");
}
Now navigate directly to /ControllerName/GetImage in your browser and you should see the image.
The next step is to fetch the image from the database and probably store it on your harddisk to ensure that it is a valid image:
type obj = _someRepository.GetType(param);
File.WriteAllBytes(#"c:\work\foo.png", obj.Image.ToArray());
Now checkout the generated file and see if it is valid. The last step is to ensure that the url generated in the <img> tag is the same as the one you used to test directly. Then look at FireBug's Net tab to see if the browser correctly requests the image and what does the server return.
Most probably the issue is that the byte array returned from the database is not valid image or it is empty.
As far as the form you have shown in your question, this is for uploading files, it has nothing to do with serving dynamic images from a controller action, so I don't see what relation it might have to your question.

How can I display an HtmlPage object (from HtmlUnit) to be opened in a real browser?

I am using Htmlunit (browser automation/testing tool) to go through a series of links or perform a set of actions on a page.
At some point after this I want to see the resulting page in a browser (internet explorer or firefox etc.)
How can I do this. ? Thank you Friends...
You can also use htmlPage.save(File) (which automatically saves images) before executing real browser
I hope I got you correctly.
This is my solution:
WebClient wc = new WebClient();
HtmlPage page = wc.getPage("http://stackoverflow.com/");
//Get page as Html
String htmlBody = page.getWebResponse().getContentAsString();
//Save the response in a file
String filePath = "c:/temp/out.html";
BufferedWriter bw = new BufferedWriter(new FileWriter(new File(filePath)));
bw.write(htmlBody);
bw.close();
//Open the page with a browser
Runtime.getRuntime().exec("C:/Program Files/Internet Explorer/iexplore.exe " + filePath);
Hope that helps.
I think this is what he had in mind
//Get page as Html <br>
HtmlPage page = wc.getPage("http://stackoverflow.com/");
//create File object <br>
File file = new File("c://temp//out");
//save page image <br>
page.save(file);
After saving the page to a file with the HtmlPage.save(File) method,
you can use the java.awt.Desktop API to open the file in its default application on your system (i.e. web browser if the file extension is ".html")
Example:
HtmlPage page = webClient.getPage("http://example.com/");
File file = File.createTempFile("example", ".html");
page.save(file);
Desktop.getDesktop().open(file);
This should work on any OS/browser.
Credit: thanks to this answer for suggesting the java.awt.Desktop solution for launching a web browser.

Resources