How do I access table elements in cheerio? - node.js

I have a Table let's say. The elements have no classes, ids or anything except a value. They only have applied style but inside the element. The rest are TD and TR's. Now in Python and BeautifulSoup4 I can do this:
status = soup.select('._lMf')
table = soup.select('.g table td')
departure = table[8].getText()
deptime = table[4].getText() + " " + table[5].getText()
terminal = table[6].getText() + " "+ table[11].getText()
arrival = table[19].getText()
arrtime = table[15].getText() + " " + table[16].getText()
arrterminal = table[17].getText() + " " + table[22].getText()
info = table[1].getText()
Select the table and the elements i'm looking for which is a TD and access them. Now I tried almost the same techniques in Cheerio but didn't do it. I got like:
TypeError: table[5].text is not a function and Objects.
It successfully logged the easiest 2 that can be directly accessed but it fails on table elements.
This is how i do it in Cheerio:
var table = $('.g table td')
var deptime = table[5]
var city = table[8].text()
var terminal = table[6].text()
Help!

Use
var table = $('.g table td')
var deptime = table.eq(5).text()
var city = table.eq(8).text()
var terminal = table.eq(6).text()

Related

How can I match exact text in a particular column and output the entire row of information?

I have been attempting to create a Telegram bot that searches a preexisting database and outputs information based on search query, essentially I want the bot to just receive a text via Telegram that contains an invoice number and output all relevant information regarding that order (The entire row of information).
Since I am dealing with invoice numbers and tracking numbers, sometimes the bot is exporting incorrect information given the current script is not matching exact text or a specific column.
For instance, rather than searching and finding invoice number it picks up a partial match of tracking number and outputs the wrong information.
I would like to set it up to search a specific column, ie. Column 3 - "Invoice #" and then output the entire row of information.
Thanks in advance!
I have been working in Google App Script:
var token = "";
var telegramUrl = "https://api.telegram.org/bot" + token;
var webAppUrl = "";
var ssId = "";
function getMe() {
var url = telegramUrl + "/getMe";
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
}
function setWebhook() {
var url = telegramUrl + "/setWebhook?url=" + webAppUrl;
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
}
function sendText(id,text) {
var url = telegramUrl + "/sendMessage?chat_id=" + id + "&text=" + text;
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
}
function doGet(e) {
return HtmlService.createHtmlOutput("Hi there");
}
function doPost(e) {
var data = JSON.parse(e.postData.contents);
var text = data.message.text;
var id = data.message.chat.id;
var name = data.message.chat.first_name + " " + data.message.chat.last_name;
var answer = "Hi " + name + ", please enter invoice number.";
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Orders");
var search_string = text
var textFinder = sheet.createTextFinder(search_string)
var search_row = textFinder.findNext().getRow();
var value = SpreadsheetApp.getActiveSheet().getRange("F"+search_row).getValues();
var value_a = SpreadsheetApp.getActiveSheet().getRange("G"+search_row).getValues();
sendText(id,value+" "+ value_a)
}
You want to find rows where the content in column 3 is exactly equal to your variable "text"
Modify your function doPost as following:
function doPost(e) {
var data = JSON.parse(e.postData.contents);
var text = data.message.text;
var id = data.message.chat.id;
var name = data.message.chat.first_name + " " + data.message.chat.last_name;
var answer = "Hi " + name + ", please enter invoice number.";
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Orders");
var range = sheet.getRange(1,1, sheet.getLastRow(), sheet.getLastColumn());
var values = range.getValues();
for (var i=0; i< values.length; i++){
var column3Value = values[i][2];
if(column3Value == text){
var rowValues = values[i].toString();
sendText(id,rowValues)
}
}
}
Explanations
The for loop iterates through all rows and compares the values in column 3 (array element[2] against the value of text
The operator == makes sure that only exact matches are found (indexOf() would also retrieve partial matches)
In case a match is found, the values from the whole row are converted to a comma separated string with toString() (You can procced the values differntly if desired)
Every row with a match will be sent to the function sendText() (you could alternatively push all rows with matches into an array / string and call sendText() only once, after exiting the for loop
I hope this answer helps you to solve your problem and adapt the provided code snippet to your needs!
I would look for a specific column where the order number is stored.
I`m not sure if it is the best way from performance side, but I think it should work.
function orderInformation(orderNumber){
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Orders");
//Gets last row in Orders sheet
var lastRow = sheet.getLastRow();
//Here you can change column where is order number stored
var orderNumberRange = sheet.getRange("A1:A" + lastRow);
//Gets all order number values
var orderNumbers = orderNumberRange.getValues();
//You can use indexOf to find which row has information about requested order
var orderLocation = orderNumbers.indexOf(orderNumber);
//Now get row with order data, lets suppose that your order information is from column A to Z
var orderData = sheet.getRange("A" + (orderLocation + 1) + ":Z" + (orderLocation + 1)).getValues();
//Now you have all data in array, where you can loop through and generate response text for a customer.
}
Sorry, I have not tested it, at the moment I don`t have time to make a test sheet, but this is the way I would do it and I think it should work.
I will test it maybe later when I will be able to make a test sheet.

Adding new element to Array - Swift 3

I have a Tableviewcontroller BeamsNameVC with 2 variables: Name and number.
If for example, the number is 7, and if I click on any row in this View controller, it will segue to another TableViewcontroller SpansListVC and than it will show 7 rows: S1, S2, S3, S4, S5, S6 & S7.
I want to save these Data, so I created 2 swift files:
class StructureElement: NSObject, NSCoding {
var name = ""
var nbrSpans = ""
var spans = [LoadDetailsForEachSpan]()
and
class LoadDetailsForEachSpan: NSObject, NSCoding {
var i_SpanName = ""
var i_Spanlength = ""
var i_ConcentratedLoadForEachSpans = [ConcentratedLoadForEachSpan]()
I created a protocol with the following:
let spanNbr = Int(structureElement[newRowIndex].nbrSpans)
let newElementDetailSpan = LoadDetailsForEachSpan()
for i in 0...spanNbr! {
newElementDetailSpan.i_SpanName = "S" + " \(i)"
structureElement[newRowIndex].spans.append(newElementDetailSpan)
}
If i run the application, it will segue to * SpansListVC* but all values are the last i.
Example:
if name is Test 7 and number of span is 7, I will be having inside *[Spans] * 7 values with the same name:
spans[0] = S 7
spans[1] = S 7
....
Any mistake with above code?
Welcome to the hell that mutable data objects can be ;). You are creating a single LoadDetailsForEachSpan instance and add that same instance a number of times to the array, while setting the i_SpanName property of that same instance every time the loop is iterated. You probably want to pull the instance creation into the loop:
for i in 0...spanNbr! {
let newElementDetailSpan = LoadDetailsForEachSpan()
newElementDetailSpan.i_SpanName = "S" + " \(i)"
structureElement[newRowIndex].spans.append(newElementDetailSpan)
}
Thanks #thm for your reply.
however, i find another solution as follow and it works:
var spanDetailAndLoadItem: [SpanDetailsAndLoads] = []
for var i in 1...nbr! {
let item = SpanDetailsAndLoads(name: "S\(i) - S\(i + 1)")
spanDetailAndLoadItem.append(item)
}
self.spans = spanDetailAndLoadItem

Adding values to multi-value field and displaying them

I have 3 multi-value fields and I have already inserted values in them. All of the fields are Text type, edible. What I'm trying to do is that I want to add functionality in xpages, so that I can add new values to those fields.
Here's what I got so far:
The code that triggers on the save button:
var statuss = document1.getItemValue("statuss");
var stat_vec:java.util.Vector = document1.getItemValue("statuss_update");
stat_vec.add(statuss);
document1.replaceItemValue("statuss_update", stat_vec);
var vards = session.getEffectiveUserName();
var vards_vec:java.util.Vector = document1.getItemValue("name_update");
vards_vec.add(vards);
document1.replaceItemValue("name_update", vards_vec);
var laiks = session.createDateTime("Today");
var laiks_vec:java.util.Vector = document1.getItemValue("time_update");
laiks_vec.add(laiks);
document1.replaceItemValue("time_update", laiks_vec);
document1.save();
The code that I have atteched to the computedField, where the values are displayed from the 3 multi value fields + it refreshes when I insert new values:
var x = document1.getItemValue("statuss_update");
var y = document1.getItemValue("name_update");
var z = document1.getItemValue("time_update");
var html = "<head><link rel=\"stylesheet\" type = \"text/css\" href=\"test.css\"></head><table id=\"tabula\">";
for (i = 0 ; i < x.size()-1; i++){
html= html + "<tr><td>" + x[i] + "</td><td>" + y[i] + "</td><td>" +z[i] + "</td></tr>";
}
html = html + "</table>";
I can insert the values and they get displayed in the HTML table but the problem is with saving the edits. Whenever I try to save the document (I have a save button that has save document event attached to it) I get the error:
Could not save the document 1B06 NotesException: Unknown or
unsupported object type in Vector
As far as I understand I'm trying to savesomething in a field, where the values type is not supported. Can anyone give me a hint what am I doing wrong or where to look for the problem? Been stuck with this for a pretty long time.
Is it this part?
var statuss = document1.getItemValue("statuss");
var stat_vec:java.util.Vector = document1.getItemValue("statuss_update");
stat_vec.add(statuss);
It looks like you're getting the statuss item's values (potentially a Vector??) and adding it to the Vector for statuss_update. If it's definitely just one value, getItemValueString() would work better.
I'm nnot sure if this is right, but you mention all fields are Text type, but it looks like you're passing a DateTime to the third one.
It might be worth analysing the contents of the Vectors before it's doing the save, just to make sure they contain what you expect.

xpages ftsearch documents from an interval of dates

I made an xpage element for ftsearch using a tutorial from IBM
My request: is there possible having 2 date fields ( as input requirements for the search ) to find those documents having the creation date inside the interval consisting of those 2 dates?
Should I create a computed field dtCreated where I will store the creation date and then in the search property of the view I should add something like this:
var tmpArray = new Array("");
var cTerms = 0;
if (sessionScope.searchDate1) && (sessionScope.searchDate2) {
tmpArray[cTerms++] = "(Field dtCreated > \"" + sessionScope.searhcDate1 + "\")" && "(Field dtCreated < \"" + sessionScope.searhcDate2 + "\")";
}
....
....
Or there is another alternative?
My 2 session variables are having Short (5/5/14) Date format. Also, my default value for those 2 dates (session variables) are "" but of course I add some values before clicking the Submit button.
Thanks for your time!
You can use the special field _creationDate as creation date (see answer from Tommy). Based on this the following example query will work in the Notes client:
Field _creationDate > 01-01-2014 AND Field _creationDate < 01-03-2014
In order to get this query to work with your specific code do this:
var tmpArray = new Array("");
var cTerms = 0;
var dateFormatter = new java.text.SimpleDateFormat( "dd-MM-yyyy" );
if (sessionScope.searchDate1) && (sessionScope.searchDate2) {
tmpArray[cTerms++] = "Field _creationDate > " + dateFormatter.format(sessionScope.searchDate1) + " AND Field _creationDate < " + dateFormatter.format(sessionScope.searchDate2);
}
If you want to do an FTSearch, _CreationDate can be used
Documentation (scroll to Searching for Header Information):
http://publib.boulder.ibm.com/infocenter/domhelp/v8r0/index.jsp?topic=%2Fcom.ibm.designer.domino.main.doc%2FH_CUSTOMIZING_SEARCH_FORMS_7304.html
E.g. (there might be typos):
tmpArray[cTerms++] = "(Field _creationDate>" + sessionScope.searhcDate1 + ") AND (Field _creationDate<" + sessionScope.searhcDate2 + ")";
Or my preferred syntax:
tmpArray[cTerms++] = "[_creationDate>" + sessionScope.searhcDate1 + "] AND [_creationDate<" + sessionScope.searhcDate2 + "]";
To build on Tommy's answer:
Specifically, try "yyyy/m/d" as the format. If those values in sessionScope are java.util.Date (the type that date fields use), you could try something like this (typing off the top of my head, not in an app, so my apologies for typos):
var tmpArray = [];
var cTerms = 0;
if(sessionScope.searchDate1 && sessionScope.searchDate2) {
var formatter = new java.text.SimpleDateFormat("yyyy/M/d");
tmpArray[cTerms++] = "[_CreationDate] >= " + formatter.format(sessionScope.searchDate1) + " and [_CreaationDate] <= " + formatter.format(sessionScope.searchDate2)
}
What you want to end up with is a FT query like:
[_CreationDate] >= 2014/1/1 and [_CreationDate] <= 2014/2/1

search view with the exact value

I have a view in which I search for products. I'm for example looking for product 1234.
The problem is their also exist products called 1234A and 1234 C etc. When I look with the code mentioned below I get all the items from product 1234 but also from 1234A and 1234 C etc.
It has to be limited to items from product 1234 only
Search code (under Data / Search in view results):
var tmpArray = new Array("");
var cTerms = 0;
if (sessionScope.SelectedProduct != null & sessionScope.SelectedProduct != "") {
tmpArray[cTerms++] = "(FIELD spareProduct = \"" + sessionScope.SelectedProduct +
"\")";
}
if (sessionScope.Development != null & sessionScope.Development != "") {
tmpArray[cTerms++] = "(FIELD spareStatus = \"*" + sessionScope.Development +
"*\")";
}
qstring = tmpArray.join(" AND ").trim();
return qstring
I used the suggestion from Frantisek :
I made a view with a combined column . (combined with the different "keys" I search for)
Then instead of using data / search , I used data/keys with exact keymatch. In this key I combined the searched items.
Since I had a field in wich I had sometimes at the end a character "°" , and it seems that this character doesn't work with a lookup , I took it out of my view and searched item with #Word(FIELDNAME; "°" ; 1).
As Frantisek suggested I could have used #ReplaceSubstring( field; "°"; "" ) also.

Resources