IT_IFRC_TS
IT_IFRC_TS

Reputation: 1

HTTR POST in r token

I want to scrape data of agents on this website: https://thep.hoaphat.com.vn/distribution-systems

I'm using the following code but get "Token mismatch error":

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)

How can I solve it?

Upvotes: 0

Views: 643

Answers (1)

xwhitelight
xwhitelight

Reputation: 1579

The data is requested to https://thep.hoaphat.com.vn/ajax/load_agency

Do a little reverse engineering, I've found the request is sent from this JS file: https://thep.hoaphat.com.vn/assets/js/functions.min.js

Take a look at this function:

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!")
        }
    })
}

You can see that the token is from the meta tag with name csrf-token. Now you can scrape that token value and send the request to get the data:

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

Result:

enter image description here

Upvotes: 1

Related Questions