Scrape a table using ScrapySharp and HtmlAgilityPack - scrapysharp

I am trying to scrape an economic calendar from a specific website. Actually, I tried many times without any success, I don't know where I am wrong. Can you help me, pls?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HtmlAgilityPack;
using ScrapySharp.Extensions;
using ScrapySharp.Network;
namespace Calendar
{
class Program
{
static void Main(string[] args)
{
var url = "https://www.fxstreet.com/economic-calendar";
var webGet = new HtmlWeb();
if (webGet.Load(url) is HtmlDocument document)
{
var nodes = document.DocumentNode.CssSelect("#fxst-calendartable tbody").ToList();
foreach (var node in nodes)
{
// event_time
Debug.Print(node.CssSelect("div div").Single().InnerText);
// event-title
Debug.Print(node.CssSelect("div a").Single().InnerText);
}
}
Console.WriteLine("");
Console.ReadLine()
}
}
}

What error are you getting?
If you want to publish the event names and times from the website, I am assuming you need to read the table.
You can do so using
HtmlNode tablebody = doc.DocumentNode.SelectSingleNode("//table[#class='fxs_c_table']/tbody");
foreach(HtmlNode tr in tablebody.SelectNodes("./tr[#class='fxs_c_row']"))
{
Console.WriteLine("\nTableRow: ");
foreach(HtmlNode td in tr.SelectNodes("./td"))
{
Console.WriteLine(td.SelectSingleNode("./span").InnerText);
}
}
Get hold of the table with the class attribute and then use relevant XPATH to traverse the elements. Please post the error you are getting with your code.

Related

HtmlAgilityPack retrieve innerText without children's Innertext

I have
<p class="MyClass">
<span>Value:</span>
12345
</p>
I'd like to retrieve only 12345, if possible, thanks
Not sure if the most elegant solution, but what about
using HtmlAgilityPack;
using System;
using ScrapySharp.Extensions;
using System.Linq;
using HtmlAgilityPack.CssSelectors.NetCore;
namespace StackOverflow
{
class Program
{
static void Main(string[] args)
{
var doc = new HtmlDocument();
doc.LoadHtml(#"<p class='MyClass'>
<span>Value:</span>
12345
</p>");
//Using ScrapySharp.Extensions
var p = doc.DocumentNode.CssSelect("p")?.FirstOrDefault();
var span = p.CssSelect("span")?.FirstOrDefault();
Console.WriteLine(p.InnerText.Replace(span.InnerHtml, string.Empty)?.Trim());
//Using HtmlAgilityPack.CssSelectors.NetCore
var results = doc.QuerySelectorAll("p")?.Select(p => p.InnerText.Replace(p.QuerySelector("span").InnerHtml, string.Empty)?.Trim());
foreach(var result in results)
Console.WriteLine(result);
}
}
}
P.S.: I am used to working with ScrapySharp in conjunction to HtmlAgilityPack, but see that there is a HtmlAgilityPack.CssSelectors.NetCore that may the common choice nowadays.

Scandit Barcode Scanner Shows Blank camera on scanning

I am trying to implement scandit barcode scanner in my application.i downloaded its sample demo and its works fine.
same code i tried to implement in my app.but it shows black screen on scanning .
I gave camera access also. cant find any thing missing.
Please help if someone also faced same issue. any suggestion most appreciated.
thanks in advance
This is my code
using FormBot.ViewModels.Abstract;
using Scandit.BarcodePicker.Unified;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using Xamarin.Forms;
namespace FormBot.ViewModels
{
public class SerialNumberViewModel: BaseViewModelDemo
{
private string _recognizedCode;
public ICommand StartScanningCommand => new Command(async () => await StartScanning());
public string RecognizedCode
{
get
{
return (_recognizedCode == null) ? "" : "Code scanned: " + _recognizedCode;
}
set
{
_recognizedCode = value;
}
}
public SerialNumberViewModel()
{
ScanditService.ScanditLicense.AppKey = "Key";
ScanditService.BarcodePicker.DidScan += BarcodePickerOnDidScan;
}
private async void BarcodePickerOnDidScan(ScanSession session)
{
RecognizedCode = session.NewlyRecognizedCodes.LastOrDefault()?.Data;
await ScanditService.BarcodePicker.StopScanningAsync();
}
private async Task StartScanning()
{
await ScanditService.BarcodePicker.StartScanningAsync(false);
}
}
}
in app.xaml.cs
private static string appKey = "key";
ScanditService.ScanditLicense.AppKey = appKey;
set android:hardwareAccelerated="true" in AndroidManifest.xml file worked for me.

How do I get self-hosted WebApi to fetch linked content?

Noob question. I have a project with a self-hosted Web Api. I'm using the RazorEngine package so that I can serve up HTML pages using the views/razor scheme.
Within the HTML page there are links to .css, .JS, and images. How does the page get these embedded resources?
As I understand it, http://localhost:8080/api/home in the browser causes the project to 'call' the page at /Views/Home.html and pass through the Value object. This results in HTML appearing in the browser rather than the usual JSON/XML that you normally get with WebAPi.
For the page to retrieve the embedded javascript, I guess I would create another WebApi controller that would respond to the URL, but how do I get it to transmit the javascript page? Ie how do I get it to look in a folder called 'Scripts' and not 'Views', not attempt to convert to HTML, and not bother with an associated model?
public class HomeController : ApiController
{
//http://localhost:8080/api/home
public Value GetValues()
{
return new Value() { Numbers = new int[] { 1, 2, 3 } };
}
}
[View("Home")]
public class Value
{
public int[] Numbers { get; set; }
}
home.cshtml...
<html>
<head>
<script src="/Scripts/script1.js"></script>
</head>
<body>
<img src="/Images/image1.png">
....
</body>
</html>
In case anyone else has this issue, this is how I did it in the end....
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Diagnostics;
using WebApiContrib.Formatting.Html;
using System.IO;
using System.Net;
using System.Drawing;
using System.Resources;
using System.Reflection;
using System.Text.RegularExpressions;
namespace Owin_Test1.Controllers
{
public class PageResourcesController : ApiController
{
//
// An HTML page will have references to css, javascript and image files
// This method supplies these file to the browser
// These files are saved in the Visual Studio project as linked resources
// Make sure the resources are names correctly (and correct case) i.e.:
// <fileName> = <resourceName>.<fileExtension>
// http://localhost:8080/api/PageResources/<fileName>
// The fileExtension is used to determine how to extract & present the resource
// (Note, <filename> is the reference in the HTML page
// - it needed be the same as the name of the actual file.)
//
public HttpResponseMessage Get(string filename)
{
String projectName = "Owin_Test1";
//Obtain the resource name and file extension
var matches = Regex.Matches(filename, #"^\s*(.+?)\.([^.]+)\s*$");
String resourceName = matches[0].Groups[1].ToString();
String fileExtension = matches[0].Groups[2].ToString().ToLower();
Debug.WriteLine("Resource: {0} {1}",
resourceName,
fileExtension);
//Get the resource
ResourceManager rm = new ResourceManager(
projectName + ".Properties.Resources",
typeof(Properties.Resources).Assembly);
Object resource = rm.GetObject(resourceName);
ImageConverter imageConverter = new ImageConverter();
byte[] resourceByteArray;
String contentType;
//Generate a byteArray and contentType for each type of resource
switch (fileExtension)
{
case "jpg":
case "jpeg":
resourceByteArray = (byte[])imageConverter.ConvertTo(resource, typeof(byte[]));
contentType = "image/jpeg";
break;
case "png":
resourceByteArray = (byte[])imageConverter.ConvertTo(resource, typeof(byte[]));
contentType = "image/png";
break;
case "css":
resourceByteArray = Encoding.UTF8.GetBytes((String)resource);
contentType = "text/css";
break;
case "js":
resourceByteArray = Encoding.UTF8.GetBytes((String)resource);
contentType = "application/javascript";
break;
case "html":
default:
resourceByteArray = Encoding.UTF8.GetBytes((String)resource);
contentType = "text/html";
break;
}
//Convert resource to a stream, package up and send on to the browser
MemoryStream dataStream = new MemoryStream(resourceByteArray);
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StreamContent(dataStream);
response.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
return response;
}
}
}

MVC3 LINQ SubmitChanges Invalid

In the method below db.SubmitChanges is shown as invalid/not recognized by intellisense.
This is my first attempt to update records in a database using LINQ and the method may contain other logic/syntactical errors that I havent yet uncovered as well. What is causing the SubmitChanges to be incorrect?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;
using System.Linq.Expressions;
public void updateInfo(RefillViewModel _myRefillViewModel) {
try {
decimal patid = _myRefillViewModel.Patient.Patient_ID;
decimal rxid = _myRefillViewModel.Rx.Rx_ID;
CAHODEntities db = new CAHODEntities();
List<Fill> FillList = db.Fills.Where(p => p.Rx.Rx_ID == rxid && p.Rx.Patient_ID == patid && p.Status == "UnFilled").ToList();
foreach (var item in FillList)
{
if (FillList.Count() == 0)
{
item.Status = "Requested";
}
}
db.SubmitChanges();
}
}
Are you using EF? Because in Entity Framework it's SaveChanges() not SubmitChanges().

Update CRM 2011 using OrganizationServiceContext

How do you update records in CRM 2011 using OrganizationServiceContext? Can anyone provide a simple example? Thanks!
This is my code:
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Description;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Client;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Linq;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Client.Services;
using System.Data.Services;
using System.Text.RegularExpressions;
using System.Web.UI.HtmlControls;
using System.Diagnostics;
using System.Web.Security;
using System.Data;
using System.Collections.Specialized;
using System.Web.SessionState;
using System;
using System.Web.Profile;
using System.Configuration;
using System.Web.UI.WebControls;
using System.Collections;
using System.Web.UI.WebControls.WebParts;
using System.Web;
using System.Web.UI;
using System.Drawing;
using System.Text;
using System.Web.Caching;
using Telerik.Web.UI;
using Microsoft.Xrm.Sdk.Discovery;
using Microsoft.Data.Entity;
using System.Data.Entity;
public partial class LeadShareEditPanel : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void imgBtnSaveNote_Click(object sender, ImageClickEventArgs e)
{
Uri organizationUri = new Uri("http://server/CRMT/XRMServices/2011/Organization.svc");
Uri homeRealmUri = null;
ClientCredentials credentials = new ClientCredentials();
credentials.Windows.ClientCredential = new System.Net.NetworkCredential("user", "password", "domain");
OrganizationServiceProxy orgProxy = new OrganizationServiceProxy(organizationUri, homeRealmUri, credentials, null);
// Get the IOrganizationService
//Get OrganizationServiceContext -the organization service context class implements the IQueryable interface and
//a .NET Language-Integrated Query (LINQ) query provider so we can write LINQ queries against Microsoft Dynamics CRM data.
using (var service = new OrganizationService(orgProxy))
using (var context = new CrmOrganizationServiceContext(service))
{
var contact = context.CreateQuery<Contact>().First(c => c.FirstName == "Bob");
contact.JobTitle = "Developer";
context.UpdateObject(contact);
context.SaveChanges();
contact.EMailAddress1 = "bob#contoso.com";
context.UpdateObject(contact);
context.SaveChanges();
}
}
}
This is an example from the 5.05 SDK help file
using (var service = new OrganizationService(connection))
using (var context = new CrmOrganizationServiceContext(service))
{
var contact = context.CreateQuery<Contact>().First(c => c.FirstName == "Bob");
contact.JobTitle = "Developer";
context.UpdateObject(contact);
context.SaveChanges();
contact.EMailAddress1 = "bob#contoso.com";
context.UpdateObject(contact);
context.SaveChanges();
}
If you haven't already you can download the SDK from here crm 2011 sdk . I would highly reccomend it as it has lots of great samples. The current version is 5.06.
Hope that helps.

Resources