-1

I wrote this code:

import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;
import com.gargoylesoftware.htmlunit.html.HtmlTextArea;
import java.util.ArrayList;
import java.util.List;

/**
*
* @author user
*/
public class YouTubeComment {

public static void main(String[] args) {
    boolean f = YouTubeLogin.login();
    try {
        if (f) {
            WebClient webClient = new WebClient(BrowserVersion.FIREFOX_3_6);
            webClient.setRedirectEnabled(true);
            webClient.setJavaScriptEnabled(false);
            HtmlPage firstPage = webClient.getPage("http://www.youtube.com/watch?v=kqDacBDoVM4&feature=related");
            List<HtmlForm> forms = new ArrayList();
            forms = (List<HtmlForm>) firstPage.getForms();
            HtmlForm form = firstPage.getForms().get(1);

            HtmlTextArea commentArea = (HtmlTextArea)form.getTextAreaByName("comment");
            commentArea.setText("good");
         HtmlSubmitInput submitButton =(HtmlSubmitInput)form.getInputByName("");
            HtmlPage pageAfterPost = (HtmlPage) submitButton.click();
        } else {
            System.out.println("Sorry..! Login is not successful");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

}

This application can login to a YouTube account with the username and password.
I want to write some code for posting comments after the successful login.
Please Help.

john_science
  • 6,325
  • 6
  • 43
  • 60
user1319054
  • 41
  • 1
  • 5

1 Answers1

0

Ok, so you should probably try to look at the HTML content of the page with Firebug on Firefox to see what are the fields to use to post a comment.

From what I've seen, you need to find a div called 'comments-view'. A bit deepers in that div, there is a form with an action /comment_servlet?add_comment=1. Then you should fill in the textarea comment (it has its name attribute set to 'comment'). Eventually, you need to find the "Publish" button and click on it.

Guillaume Polet
  • 47,259
  • 4
  • 83
  • 117
  • by writing this code: HtmlForm form = firstPage.getFormByName("/comment_servlet?add_comment=1"); its throwing an exception, com.gargoylesoftware.htmlunit.ElementNotFoundException: elementName=[form] attributeName=[name] attributeValue=[/comment_servlet?add_comment=1] at com.gargoylesoftware.htmlunit.html.HtmlPage.getFormByName(HtmlPage.java:562) at htmlunitexample.YouTubeComment.main(YouTubeComment.java:32) – user1319054 Apr 14 '12 at 10:01
  • the form does not have a name, it only as an action and class which is not sufficient to find it. What you can do is find the div with id 'comments-view' and inside find the form, using `getHtmlElementsByTagName` (there should be only one) – Guillaume Polet Apr 14 '12 at 10:50