开发者

How to copy text from a browser with Java?

Is there a way to copy text from a browser to my Java app ?

For example, at the left side of my screen I open a browser to point to a URL and shows the content of that page, it might be in a frame or CSS or simple html, on the right side of the screen I open a Java Swing application. I'm interested in certain parts of the browser window that shows some开发者_StackOverflow text, and I want my Java app [ without me doing anything ] to copy and paste the text into itself, can it be done ?

I know I can use JEditorPane or JTextPane and set it with an HTMLEditorKit, then load the text into the pane, but if the page uses Frames or some other complex ways, the text I get from the Pane is not what I see on the page, so I don't want to do it by loading the URL into my Java app, instead, I wonder if it can be done in the way I mentioned above ?


I think you're looking at the problem from the wrong angle. If what you want is to harvest a website, I suggest you have a look at the awesome library web-harvest. With a little Xpath wizardry you can get everything you want. Doing what you describe would imply inter-process communication that seems like an overkill. There are more ways to download a web-page content than the browser.


You may try the following depending on your needs.

With java.awt.Robot you can either 1) Take an screenshot if what you neeed is the content ( without the text, just an image of the browser content ) or 2) Move your self into the browser and programatically press: CTRL-A + CTRL-C and return back to your swing app focus and programatically press: CTRL-V ( or CMD or whatever makes sense in your OS )

But again, this might or not work, depending on what you need.


I know a tool but i am not sure it meet your needs. Have you heard about selenium? http://seleniumhq.org/ It can replicate actions taken by the user in a browser and then manipulate them ussing java code. Have a look at the link it may be handy.


Using java.awt.Robot & a TextField will get the job done, not sure if there is any other way. Have robot press ctrl+a then ctrl+c, bring TextField into focus, and finally have robot press ctrl+v. Now from here you can create a button.setOnAction to save the TextField text into a string. Or you can use a change listener on the TextField setOnKeyReleased to do the same.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜