使用JSOUP登录Github



我的代码现在是这样的(过时的示例代码?(,我想使用JSOUP登录GitHub。但当我尝试运行此程序时,出现了一个错误。我在下面标记了我得到错误的地方,我认为代码没有使用正确的cssquery,因为它已经过时了。

try {
// # Constants used in this example
final String USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 
(KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36";
final String LOGIN_FORM_URL = "https://github.com/login";
final String LOGIN_ACTION_URL = "https://github.com/session";
final String USERNAME = "user";
final String PASSWORD = "pass";
// # Go to login page and grab cookies sent by server
Connection.Response loginForm = Jsoup.connect(LOGIN_FORM_URL)
.method(Connection.Method.GET)
.userAgent(USER_AGENT)
.execute();
Document loginDoc = loginForm.parse(); // this is the document containing response html
HashMap<String, String> cookies = new HashMap<>(loginForm.cookies()); // save the cookies to be passed on to next request
// # Prepare login credentials
**// This is where I get an error.**
String authToken = loginDoc.select("#login > form > div:nth-child(1) > input[type="hidden"]:nth-child(2)")
.first()
.attr("value");
HashMap<String, String> formData = new HashMap<>();
formData.put("commit", "Sign in");
formData.put("utf8", "e2 9c 93");
formData.put("login", USERNAME);
formData.put("password", PASSWORD);
formData.put("authenticity_token", authToken);
// # Now send the form for login
Connection.Response homePage = Jsoup.connect(LOGIN_ACTION_URL)
.cookies(cookies)
.data(formData)
.method(Connection.Method.POST)
.userAgent(USER_AGENT)
.execute();
System.out.println(homePage.parse().html());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

您得到这个错误是因为select找错了地方。(它正在查看div元素内部,但您想要的字段已不在其中。(好消息是,现在可以更容易地选择auth令牌:

String authToken = loginDoc.selectFirst("input[name=authenticity_token]") != null ? loginDoc.selectFirst("input[name=authenticity_token]").val() : null;

坏消息是,表单现在还需要其他一些数据,您需要执行一系列类似的select语句来获取所有数据,并执行formData.put语句来将它们传递给post。

  • trusted_device:
  • webauthn支持:
  • webauthn-iuvpaa支持:
  • return_to:
  • allow_signup:
  • client_id:
  • 集成:
  • required_field_392c:
  • 时间戳:
  • 时间戳_机密:

正如评论中所建议的,使用API可能是";经得起未来考验";应用程序,以避免这种不愉快的事情发生。

最新更新