Проблема входа в Jsoup (URL / cookie / сеанс / POST / данные) - PullRequest
0 голосов
/ 03 января 2019

Моя цель - войти на этот сайт .

После обхода по различным темам:
- jsoup отправка и cookie
- Войдите в Facebook с помощью Jsoup и правильных файлов cookie
- Как опубликовать форму входа с помощью jsoup?
- Невозможно войти на сайт с помощью jsoup

Я наконец-то придумал этот тестовый класс:

public class JsoupTest {
    public static void main(String args[]) throws URISyntaxException {
        try {

            String urlLogIn = "https://invest.firstrade.com/cgi-bin/login";

            // Put the url that you see when you have logged in.
            String urlUnderTest = "https://invest.firstrade.com/cgi-bin/main#/cgi-bin/acctpositions"; 

            // lets make data map containing all the parameters and its values found in the form
            Map<String, String> mapParams = new HashMap<String, String>();
            mapParams.put("redirect", "");
            mapParams.put("ft_locale", "en-us");
            mapParams.put("login.x", "Log In");
            mapParams.put("username", "MY_USERNAME");
            mapParams.put("password", "MY_PASSWORD");
            mapParams.put("destination_page", "acctpositions");

            print("started");

            // With this you login and a session is created
            Connection.Response res = Jsoup.connect(urlLogIn)
                    .data(mapParams)
                    .method(Method.POST)
                    .execute();

            // This will get you cookies
            Map<String, String> loginCookies = res.cookies();

            // Here you parse the page that you want.
            Document doc = Jsoup.connect(urlUnderTest).cookies(loginCookies).get();

            System.out.println(doc.title());
            print(doc.toString());

            print("done");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void print(String msg, Object... args) {
        System.out.println(String.format(msg, args));
    }
}

К сожалению, независимо от того, что я изменяю, я застреваю на странице с надписью "сеанс не удался".

<html>
 <head>
  <script>window.location = "/cgi-bin/sessionfailed?reason=6"</script>
 </head>
 <body>
  Please login first.
  <br>
  <br>
  <a href="/cgi-bin/login">Go to Login Page</a>
  <br>
 </body>
</html>

Однако я могу использовать этот класс для успешного входа в Facebook, используя URL-адрес, указанный в этой теме:
- https://stackoverflow.com/a/49984544/10857019

Jsoup.connect("https://m.facebook.com/login/async/?refsrc=https%3A%2F%2Fm.facebook.com%2F&lwv=100")

Так что я совершенно запутался, если проблема в URL s или cookie / сеанс или что-то еще?

Любая помощь будет принята с благодарностью.Большое спасибо за чтение этой темы!

1 Ответ

0 голосов
/ 12 января 2019

Спасибо за Комментарий Фредерика .

Я сам разобрался с ответом.
В этом случае мне не хватало постоянных файлов cookie .
В приведенном ниже решении I

  1. Создать карту (назовите ее session) для хранения этих данных
  2. Обновляйте ее каждый раз, когда я отправляю запрос, используя putAll метод
    session.putAll(resp.cookies());
  3. Включить эту карту в следующий запрос
    .cookies(session)

Обратите внимание, что 2и 3 должны повторяться в каждом последующем запросе.
В основном это все!

public class JsoupTest {
    public static void main(String args[]) throws URISyntaxException {
        try {

            String urlLogIn = "https://invest.firstrade.com/cgi-bin/login";

            // Put the url that you see when you have logged in.
            String urlUnderTest = "https://invest.firstrade.com/cgi-bin/main#/cgi-bin/acctpositions"; 

            // Create a "session" map here to persists cookies across all requests
            Map<String, String> session = new HashMap<String, String>();

            // get initial login form
            Response loginForm = Jsoup.connect(urlLogIn)
                    .userAgent(agent)
                    .method(Method.GET)
                    .execute();

            // initialize session
            session = loginForm.cookies();



            print("started");



            // data map containing all the parameters and its values found in the form
            Map<String, String> mapParams = new HashMap<String, String>();
            mapParams.put("redirect", "");
            mapParams.put("ft_locale", "en-us");
            mapParams.put("login.x", "Log In");
            mapParams.put("username", "MY_USERNAME");
            mapParams.put("password", "MY_PASSWORD");
            mapParams.put("destination_page", "acctpositions");

            // With this you login and a session is created
            Connection.Response res = Jsoup.connect(urlLogIn)
                    .userAgent(agent)
                    .data(mapParams)
                    .cookies(session)
                    .method(Method.POST)
                    .execute();

            // update session after login
            session.putAll(loginResp.cookies());



            print("done");



            // The snippet from "started" to "done" is a full cycle
            // From here on every request is basically as the snippet above
            // For example:
            mapParams = new HashMap<String, String>();
            mapParams.put("other required form data", "DATA");

            resp = Jsoup.connect(urlUnderTest)
                    .userAgent(agent)
                    .data(mapParams)
                    .referrer("https://invest.firstrade.com/cgi-bin/main") // sometimes referrer is necessary
                    .cookies(session)
                    .method(Method.POST)
                    .execute();
            session.putAll(resp.cookies());

            // Then you start your crawler stuff
            Document doc = resp.parse();
            System.out.println(doc.title());
            print(doc.toString());

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void print(String msg, Object... args) {
        System.out.println(String.format(msg, args));
    }
}
...