我正在尝试编写一个可以自动登录 Facebook 的 Java 程序。
到目前为止,我已经得到了以下代码,可以将主页 html 页面下载到字符串中,但不知道如何发送电子邮件和密码来登录 Facebook? Java 程序还需要处理返回的 cookie 以保持登录状态吗?
public static void main(String[] args) throws Exception {
URL url = new URL("http://www.facebook.com/");
URLConnection yc = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(yc
.getInputStream()));
String inputLine;
String allInput = "";
while ((inputLine = in.readLine()) != null) {
allInput += inputLine + "\r\n";
}
System.out.println(allInput);
in.close();
}
}
Update:
我已经使用 htmlUnit 尝试了以下代码,但是出现以下异常:
Exception in thread "main" com.gargoylesoftware.htmlunit.ElementNotFoundException: elementName=[form] attributeName=[name] attributeValue=[login_form] at com.gargoylesoftware.htmlunit.html.HtmlPage.getFormByName(HtmlPage.java:588)
有谁知道这是为什么吗?
final WebClient webClient = new WebClient();
final HtmlPage page1 = webClient.getPage("http://www.facebook.com");
final HtmlForm form = page1.getFormByName("login_form");
final HtmlSubmitInput button = (HtmlSubmitInput) form.getInputsByValue("Login").get(0);
final HtmlTextInput textField = form.getInputByName("email");
textField.setValueAttribute("[email protected] /cdn-cgi/l/email-protection");
final HtmlTextInput textField2 = form.getInputByName("pass");
textField2.setValueAttribute("ahhhh");
final HtmlPage page2 = button.click();
您的代码存在一些问题
- is that
login_form
不是表单名称而是表单 ID
- 提交按钮值 i
Log In
- 密码字段的类型是
HtmlPasswordInput
so:
final WebClient webClient = new WebClient();
final HtmlPage page1 = webClient.getPage("http://www.facebook.com");
final HtmlForm form = (HtmlForm) page1.getElementById("login_form");
final HtmlSubmitInput button = (HtmlSubmitInput) form.getInputsByValue("Log In").get(0);
final HtmlTextInput textField = form.getInputByName("email");
textField.setValueAttribute("[email protected] /cdn-cgi/l/email-protection");
final HtmlPasswordInput textField2 = form.getInputByName("pass");
textField2.setValueAttribute("ahhhh");
final HtmlPage page2 = button.click();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)