[英]HTTR POST in r token
我想在這個網站上抓取代理數據: https : //thep.hoaphat.com.vn/distribution-systems
我正在使用以下代碼,但收到“令牌不匹配錯誤”:
httr::POST(
url = "https://thep.hoaphat.com.vn/ajax/load_agency",
body = list(
type = "web",
product_id = "7",
province_id = "10",
member_type = "1"
),
encode = "form"
) -> res
dat <- httr::content(res)
str(dat)
我該如何解決?
數據請求到https://thep.hoaphat.com.vn/ajax/load_agency
做一點逆向工程,我發現請求是從這個 JS 文件發送的: https : //thep.hoaphat.com.vn/assets/js/functions.min.js
看看這個函數:
function loadAjax(t, e, n) {
var a = {
beforeSend: function() {},
success: function() {}
};
$.extend(a, n),
$.ajax({
headers: {
"X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content")
},
type: "POST",
url: t,
data: e,
beforeSend: function() {
$("#loading_box").css({
visibility: "visible",
opacity: 0
}).animate({
opacity: 1
}, 200),
a.beforeSend()
},
success: function(t) {
$("#loading_box").animate({
opacity: 0
}, 200, function() {
$("#loading_box").css("visibility", "hidden")
}),
a.success(t)
},
error: function(t) {
$("#loading_box").animate({
opacity: 0
}, 200, function() {
$("#loading_box").css("visibility", "hidden")
}),
alert("Có lỗi xảy ra!")
}
})
}
您可以看到令牌來自名為csrf-token
的meta
標記。 現在您可以抓取該令牌值並發送請求以獲取數據:
library(rvest)
pg <- html_session("https://thep.hoaphat.com.vn/distribution-systems")
token <- read_html(pg) %>%
html_node(xpath = "//meta[@name='csrf-token']") %>% html_attr("content")
pg <-
pg %>% rvest:::request_POST(
"https://thep.hoaphat.com.vn/ajax/load_agency",
config = httr::add_headers(`x-csrf-token` = token),
body = list(
type = "web",
product_id = 1, # choose product
province_id = 50, # choose province
`member_type[]` = 1, # agency level 1
`member_type[]` = 2 # agency level 2
)
)
data <- httr::content(pg$response)$data
結果:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.