Utilizing JavaScript to retrieve post requests and incorporating them with cURL/RCurl

Trying to access the page investing.com/rates-bonds/brazil-10 using RCurl and attempting to modify the default time series range through the calendar control on the main table.

Upon inspecting with Firefox Firebug, I captured the post log generated after clicking the -> Apply button on the calendar. A similar method can be executed using Log XMLHTTPRequests in Chrome.

Following the button click, the Firebug Console displays the line:

 POST http://www.investing.com/instruments/HistoricalDataAjax

Upon expanding the line, the Headers tab reveals the request header:

Request Headers
Accept             text/plain, */*; q=0.01
Accept-Encoding    gzip, deflate
Accept-Language    en-gb,en;q=0.5
Content-Length     102
Content-Type       application/x-www-form-urlencoded; charset=UTF-8
Cookie             ... very long string
Host               www.investing.com
Referer            http://www.investing.com/rates-bonds/brazil-10-year-bond-yield-historical-data
User-Agent         Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0
X-Requested-With   XMLHttpRequest

The Post tab provides:

Parameters application/x-www-form-urlencoded
action        historical_data
curr_id       24029
end_date      05/30/2014
interval_sec  Daily
st_date       05/25/2014

Based on these findings, an attempt was made to retrieve the page with:

require(RCurl)
link="http://www.investing.com/instruments/HistoricalDataAjax"
html= postForm(
    link,
    action="historical_data",
    curr_id="24029",
    end_date="05/30/2014",
    interval_sec="Daily",
    st_date="05/25/2014",
    .opts=list(
        referer="http://www.investing.com/rates-bonds/brazil-10-year-bond-yield-historical-data",
        useragent="Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0"
))

However, the result obtained was:

html
## [1] ""
## attr(,"Content-Type")
##                 charset 
## "text/html"     "utf-8" 

An alternative approach was also attempted...

cookie="...  long cookie string"
link="http://www.investing.com/instruments/HistoricalDataAjax"
h <- basicTextGatherer()
h$reset()
curlPerform(url = link,
            httpheader=c(                
                'Accept'="text/plain, */*; q=0.01",
                'Accept-Encoding'="gzip, deflate",
                'Accept-Language'="en-gb,en;q=0.5",
                'Content-Length'="102",
                'Content-Type'="application/x-www-form-urlencoded; charset=UTF-8",
                'Cookie'=cookie,
                'Host'="www.investing.com",
                'Referer'="http://www.investing.com/rates-bonds/brazil-10-year-bond-yield-historical-data",
                'User-Agent'="Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0",
                'X-Requested-With'="XMLHttpRequest"
                ),
            postfields=c(
                action="historical_data",
                curr_id="24029",
                end_date="05/30/2014",
                interval_sec="Daily",
                st_date="05/25/2014"
                ),
            writefunction = h$update,
            verbose = TRUE)
h$value()

Seeking assistance for this issue.

Answer №1

To successfully make a POST request, it is essential to configure the user-agent, origin, and x-requested-with headers.

library(httr)
url  <- "http://www.example.com/data"

POST(url, 
  body = list(
    action = "get_data",
    id = "12345",
    date = "09/15/2021",
    format = "json"
  ), 
  add_headers(
    "user-agent" = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36",
    Origin = "http://www.example.com",
    "X-Requested-With" = "XMLHttpRequest"
  ),
  encode = "form"
)

(I prefer using httr over RCurl::postForm() as it provides clearer insights into the content of the POST request).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue regarding alignment in quill-image-resize-vue

There is an issue with the alignment of images when using "quill-image-resize-vue" - they are supposed to align to the center or right, but end up being left aligned in the result. This inconsistency does not occur in all cases, and it's been challen ...

Node.js is throwing a JSON parsing error due to an unexpected end of input

Currently, I am attempting to analyze the JSON data that is returned using the following PHP code snippet; $UserData = $con->query("SELECT * FROM Discord WHERE RobloxID=".$UserId) or trigger_error($mysqli->error); $result = $UserData->fetch_a ...

Why is the "module" field used in the package.json file?

Recently, I came across certain npm packages such as vue that contain a module field in their package.json files. Interestingly, the official documentation for package.json does not mention the module field - is this some kind of convention being followed ...

Model binding in AngularJS can become broken if it is removed from the application

I'm currently working on an AngularJS application that is designed to generate multiple choice quizzes. The questions and corresponding choices are managed within the following model. $scope.testFormChoiceCount = [ {question: '', choices: [ ...

Getting data sent via Ajax and jQuery through window.location.href in a new controller in CodeIgniter

How to retrieve ajax jquery data passed through window.location.href in a new controller using CodeIgniter? $(".x").on("click","a.p",function(){ productId = $(this).attr("productId"); alert("product ID : " + product ...

Utilizing jQuery's AJAX method to redirect user upon button click

Just dipping my toes into the world of jQuery AJAX and I'm facing a conundrum. I need to redirect the user to another webpage upon clicking a button, but I can't just target the button directly due to some PHP file intricacies... Here's the ...

Replacing URLs in Typescript using Ionic 3 and Angular

Currently facing some difficulties getting this simple task to work... Here is the URL format I am dealing with: https://website.com/image{width}x{height}.jpg My objective is to replace the {width} and {height} placeholders. I attempted using this func ...

The behavior of AngularJS checkbox and ng-change is definitely puzzling

I am facing an issue with my array structure: { key : 'abc', color: 'Red', show: true } <div ng-repeat="x in myArray"> <input type="checkbox" ng-model="x" ng-change="changeShow($index)" checked="checked" /> ...

"What is the best way to indicate that the most recent web service call has finished in a Javascript

I am trying to execute the following code block: this.setState({ // <------------ REF 1 pages: pages }); only after all axios.get('https://graph.facebook.com/v5.0/' + page.id + '/events?access_token=' + accessToken) requests have ...

What is the best way to remove a specific section of HTML using cheerio?

Looking for a solution in JavaScript to extract the content from an HTML element excluding specific elements with an ID of #F1. The following code snippet is what I have tried, but it does not seem to work as expected: "use strict"; let sample ...

Exploring the Significance of jQuery in a Real-

I manage a large website with an extensive amount of jQuery code spread across multiple pages. The total codebase is around 1000 lines, well-optimized and excluding plugins. Despite jQuery being efficient in ignoring listeners for non-existent page elemen ...

What is the alternative to $templateCache in Angular2 and how can CachedResourceLoader be utilized in its place?

While I have come across 2 similar questions on Stack Overflow and here, none of them seem to provide a solution. After delving into the Angular repository, I stumbled upon this issue where they inquire about an alternative for templateCache in Angular 2, ...

Vue.JS encounter a hiccup while attempting to store data in the local storage

My application is set up to fetch data from a rest api, and it consists of two key components: 1 - (main) Display the results 2 - (list) To display a list of selected items from the main results The feature I am trying to implement involves adding a save ...

Is there a way to instantly create hyperlinks for text that follows the @ symbol?

I am looking for a way to automatically link mentions of user accounts on my website, such as @Melon or @Banana, using JavaScript. For example, I want @Banana to be linked to example.com/users/Banana. Additionally, I would like the linking functionality to ...

Incorporating scripts into AngularJS interface

Here is the content of my view: <headers> <h1>My Page</h1> </headers> <link rel="stylesheet" href="css/some.css"/> <script ng-src="js/my-view-script.js"></script> After loading the view, I noticed that the ...

Incorporating jQuery into Rails 6.1

I encountered some difficulties while setting up jQuery in rails 6.1, even though I believe it's configured correctly. Below are the steps I've taken: Installed yarn add jquery 2. In config/webpack/environments.js, I made the following changes ...

Updating a useState hook in react with a specific condition: a step-by-step guide

Utilizing react hooks (useEffect and useState) in conjunction with firebase has been a seamless process for me. Having a collection of users that can be easily retrieved from firebase, the basic structure of my code appears as follows: const [users, setUs ...

Configuring unique capabilities for the Selenium WebDriver

My goal is to customize the settings of a Selenium Webdriver. In this particular case, I am looking to modify a capability of the webdriver specifically for the Firefox browser. All of this needs to be done using Javascript. this.driver = new selenium.Bu ...

Attempting to compute the overall score by aggregating the values of answers in react.js/javascript

Can you answer this? class PopQuiz extends React.Component { constructor() { super(); this.answers = []; this.answers.push([ { value: 1, text: "pizza" }, { value: 2, text: "pasta" }, ...

What is the method for determining the y angle between two vectors using Three.js?

When working with Three.js, I encountered a challenge involving 2 3D vectors and the need to determine the angle between them along both the x-axis and y-axis. To calculate the x-axis angle, I used the following formula: toDegrees(atan2(A.z, A.y) - atan2( ...