java - 使用 Jsoup 登录和导航
问题描述
我正在尝试使用 JSoup 登录网站,我的目标是从网站上抓取一些数据,但我在登录/导航时遇到了一些问题。
有关代码当前的外观,请参见下面的代码。
try {
Connection.Response response = Jsoup.connect("https://app.northpass.com/login")
.method(Connection.Method.GET)
.execute();
response = Jsoup.connect("https://app.northpass.com/login")
.data("educator[email]", "email123")
.data("educator[password]", "password123")
.cookies(response.cookies())
.method(Connection.Method.POST)
.execute();
// Go to new page
Document coursePage = Jsoup.connect("https://app.northpass.com/course")
.cookies(response.cookies())
.get();
System.out.println(groupPage.title());
} catch (IOException e) {
e.printStackTrace();
}
我也尝试过添加
.data("commit", "Log in")
和
.userAgent("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.21 (KHTML, like Gecko) Chrome/19.0.1042.0 Safari/535.21")
没有任何成功。
我得到的错误如下:
org.jsoup.HttpStatusException: HTTP error fetching URL. Status=500, URL=https://app.northpass.com/login
根据我在其他线程上阅读的内容,人们建议使用 userAgent(如上所述,我已经尝试过)。提前感谢您的帮助。
解决方案
如果您在浏览器中尝试登录时查看网络流量,您会看到发送了额外的数据项:authenticity_token
. 这是表单中的隐藏字段。
然后,您需要从初始响应中提取它并使用 POST 请求发送它:
try {
Connection.Response response = Jsoup.connect("https://app.northpass.com/login")
.method(Connection.Method.GET)
.execute();
//I can't test this but will be something like
//see https://jsoup.org/cookbook/extracting-data/selector-syntax
Document document = response.parse();
String token = document.select("input[hidden]").first().val();
response = Jsoup.connect("https://app.northpass.com/login")
.data("educator[email]", "email123")
.data("educator[password]", "password123")
.data("authenticity_token", token)
.cookies(response.cookies())
.method(Connection.Method.POST)
.execute();
// Go to new page
Document coursePage = Jsoup.connect("https://app.northpass.com/course")
.cookies(response.cookies())
.get();
System.out.println(groupPage.title());
} catch (IOException e) {
e.printStackTrace();
}
推荐阅读
- filter - 根据多个条件创建过滤列表
- android - 日历提供程序不提供最新数据
- python - 如何制作功能“列表”?
- salesforce - LWC,使用wire和Apex从JavaScript设置记录到数据库soql,错误
- react-native - 一组值不翻译视图的最基本示例
- arrays - 创建以 false 初始化的 100 个元素的布尔值列表的最优雅方法是什么
- mysql - 如何解决用户输入的双重mysql查询?
- rust - 为什么连接到本地 EventStoreDB 时收到“收到损坏消息”?
- c++ - ASIO:在一个 io_context 中使用多个链和线程时出现死锁
- python - 从文档中收集所有 n-gram(及其频率)