Web scraping with Google Apps Script - google-apps-script

I'm trying to pull data from the following sample web page using Google Apps Script:
url = http://www.premierleague.com/players/2064/Wayne-Rooney/stats?se=54
using, UrlFetchApp.Fetch(url)
The problem is when I use UrlFetchApp.Fetch(url) to do that, I don't get the page information defined by the 'se' parameter in the url. Instead, I get the information on the following URL because it looks like the 'se=54' page is asynchronously loaded:
http://www.premierleague.com/players/2064/Wayne-Rooney/stats
Is there any way to pass the parameter 'se' some other way? I was looking at the function and it allows the specification of 'options', as they are referred to, but the documentation on the topic is very limited.
Any help would be most appreciated. Many thanks
Tommy

Go to that website in your browser and open the developer tools (F12 or ctr-shift-i). Click on the network tab and reload the page with F5.
A list of requests will appear. At the bottom of the list you should see the asynchronous requests made to fetch the information. Those requests get the data in json form from footballapi.pulselive.com.
You can do the same thing in apps script. But you have to send a correct "origin" header line or your request gets rejected.
Here is an example.
function fetchData() {
var url = "http://footballapi.pulselive.com/football/stats/player/2064?comps=1";
var options = {
"headers": {
"Origin": "http://www.premierleague.com"
}
}
var json = JSON.parse(UrlFetchApp.fetch(url, options).getContentText());
for(var i = 0; i < json.stats.length; i++) {
if(json.stats[i].name === "goals") Logger.log(json.stats[i]);
}
}

Please try the following solution:
var options =
{
"method" : "GET",
"followRedirects" : true,
"muteHttpExceptions": true
};
var result = UrlFetchApp.fetch(url, options);

Related

Adding a doPost and doGet into google app script ("GAS") code

I am a total newbie when it comes to programming.
I have put a very simple switchbot script into google app script ("GAS") to make the switchbot bot do a press. While it can run when clicking on the "run" button in GAS, when sending a http post (i.e. via android's HTTP Shortcut app) to GAS, it connects but the action fails.
I do understand later that a doPost or doGet is required to run it when sending a post to the script from an external source, but after trying various methods with doPost and doGet, I still have no idea how to integrate it or where to put it into the code.
The code is below:
function main() {
var headers = {
"Authorization" : "SWITCHBOT_TOKEN_KEY",
"Content-type" : "application/json; charset=utf-8"
};
var data = {
"command" : "press",
"parameter" : "default",
"commandType": "command"
};
var options = {
'method' : 'post',
"headers" : headers,
muteHttpExceptions : true,
"payload" : JSON.stringify(data)
};
var deviceid = "INSERT_SWITCHBOT_DEVICEID";
var url1 = https://api.switch-bot.com/v1.0/devices/${deviceid}/commands;
var response = UrlFetchApp.fetch( url1, options );
var json = JSON.parse( response.getContentText() );
console.log( json )
}
Any assistance or lesson on how to do / understand this would be great!
Tried checking and looking at various codes with dePost and doGet and integrating it into the code but all seems not work.
While it connects to GAS via the deployed web app link, I am not able to get the actual script running. It simply logs it as failed in the GAS.

Send Form response from prefilled link in Apps Script

I've tried to find some topic about it but without results
I would need only send Form from copied prefilled link in apps script but i am not able to find out where doing misstakes.
Here are two options what i've found but without good results.
Form doesn't send any response
I've replace in prefilled Link "viewform" for "formResponse" according to some instructions in web, but it does't work.
Do you can help me anyone?
function send() {
var config = {
muteHttpExceptions: true,
method: "get"
};
var url = "https://docs.google.com/forms/d/e/<form_id>/formResponse?usp=pp_url&entry.231322462=ANO&entry.133135319=1&entry.1743053173=2023-01-15";
var response = UrlFetchApp.fetch(url, config);
//Logger.log(response)
}
or:
function send() {
var url = "https://docs.google.com/forms/d/e/<form_id>/formResponse?usp=pp_url&entry.231322462=ANO&entry.133135319=1&entry.1743053173=2023-01-15";
var response = UrlFetchApp.fetch(url);
//Logger.log(response)
}
You have an existing Google Form and you want to write a script in order to edit existing Form Responses in in the Form.
At the time of writing, this isn't possible.
Refer:
Edit Form Responses as soon as it is submitted

How can I process the response to this POST request in Google Apps Script?

I am trying to use Google Apps Script to scrape the first ten results of this page: https://www.tenderboard.gov.bh/Tenders/Opened%20Bids/.
Currently, I have written the POST request to the website. However, the response is coming back in a format that I am unsure how to process. The code I have written so far looks like this:
function fetchData() {
var url = "https://www.tenderboard.gov.bh/Templates/TenderBoardWebService.aspx/GetOpenedTenderF";
var formData = {
"tenderNumber":"",
"ministry":"0",
"category":"0",
"openedDate_filter":"",
"sortingType":"0",
"pageIndex":"2"
};
var payload = JSON.stringify(formData);
var params = {
"method":"post",
"contentType":"application/json; charset=UTF-8",
"payload":payload
};
var response = UrlFetchApp.fetch(url,params);
To illustrate its format, a sample of the response is:
{"d":"\u003cNewDataSet\u003e\r\n \u003cPager\u003e\r\n \u003cPageIndex\u003e1\u003c/PageIndex\u003e\r\n \u003cPageSize\u003e10\u003c/PageSize\u003e\r\n \u003cRecordCount\u003e3799\u003c/RecordCount\u003e\r\n \u003cContent\u003e\u0026lt;div class=\u0027table-head\u0027 style=\u0027display: table-header-group; opacity: 1;\u0027\u0026gt;\u0026lt;div class=\"column\" data-label=\"No.\"\u0026gt;No.\u0026lt;/div\u0026gt;\u0026lt;div class=\"column\"
How would I go about extracting the contents of this response to build a 2D array containing the same information as the web page?
Many thanks and apologies for what I am sure is a dense question.

how to send data from telegram bot inline keyboard to specific column in google spreadsheet?

I am not really familiar with the Telegram API and need to use JSON.
I want to create an inline keyboard that have options [yes/no] only.
Then, send it to a spreadsheet.
I managed to create the inline keyboard but nothing happens when I press it.
Is it possible to send data to a spreadsheet from the Telegram bot?
Code:
{"inline_keyboard":[[{"text":"yes","callback_data":"yes"}]]}
Yes, this is possible :)
You'd first need to setup a webhook for your telegram bot -
var telegramToken = 'Your-Telegram-Bot-Token-Goes-Here';
function setup() {
var method = 'setWebhook';
var payload = {
url: ScriptApp.getService().getUrl()
}
var options = {
'method' : 'post',
'contentType': 'application/json',
'payload' : JSON.stringify(payload)
};
var response = UrlFetchApp.fetch('https://api.telegram.org/bot' + telegramToken + '/' + method, options);
Logger.log(response);
}
and then setup a simple doPost(e) to capture incoming data from said webhook. You can refer some of the code from a bot that's i'd built here but please feel free to share more details with what you require so I could assist accordingly.

Getting Error Daily Limit for Unauthenticated Use Exceeded in Google Sheets for URL Shortener API

I am getting "Error Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup" in google sheets with using URL Shortener API (image as below)
Below is my code in Script Editor
function shortenURL(urlField) {
var toShorten = UrlShortener.newUrl().setLongUrl(urlField);
var shortened = UrlShortener.Url.insert(toShorten);
return shortened.getId();
}
I have bonded to the API through Google Sheets build-in setting from "Cloud Platform Project", enabled URL Shortener API in "Advanced Google Services", enabled it in Google API Console, and created both API and OAuth (image as below). Besides, I was just using it for less than 20 cells in the Google Sheets, and so I am sure it is way less than the quote given by Google.
Cloud Platform Project
Advanced Google Services
Enable in Google API Console
If I use the below code (mentioned here), it works fine.
However, I want the script to run automatically as the function instead of by clicking the button. Therefore, I still want to solve the error.
function onOpen() {
SpreadsheetApp.getUi()
.createMenu("Shorten")
.addItem("Go !!","rangeShort")
.addToUi()
}
function rangeShort() {
var range = SpreadsheetApp.getActiveRange(), data = range.getValues();
var output = [];
for(var i = 0, iLen = data.length; i < iLen; i++) {
var url = UrlShortener.Url.insert({longUrl: data[i][0]});
output.push([url.id]);
}
range.offset(0,1).setValues(output);
}
I found some post mentioned the solution to this error is to apply authentication to the requests to Google. However, I have already created API key and OAuth and bond them to Google Sheets through those Google Sheets build-in setting.
Is there any solution to the error?
If the error occurs due to authentication issue, how I can apply the authentication in addition to those setting I have already done?
Try sending a POST request to UrlShortener API endpoint instead of using the UrlShortener service in Apps Script. With UrlShortener.Url.insert(), I quickly hit the usage quota.
Append the API url with the 'key' parameter and set it equal to the API key you obtained from Developer console.
In the body of your POST request, set 'muteHttpExceptions' to 'true' to log all error messages as beautified JSON.
var API_KEY = "YOUR_API_KEY";
function shortenUrl(longUrl) {
var apiEndpoint = "https://www.googleapis.com/urlshortener/v1/url?key=" + API_KEY;
var data = {
"longUrl": longUrl
}
var options = {
"method": "post",
"contentType": "application/json",
"muteHttpExceptions": true,
"payload": JSON.stringify(data)
};
var response = UrlFetchApp.fetch(apiEndpoint, options).getContentText();
var data = JSON.parse(response);
return data.id;
}