Readdy Write  
0,00 €
Your View Money
Views: Count
Self 20% 0
Your Content 60% 0

Users by Links 0
u1*(Content+Views) 10% 0
Follow-Follower 0
s2*(Income) 5% 0

Count
Followers 0
Login Register as User

UWP Webroboter mit SQlite Datenbank

30.06.2018 (👁23155)

UWP Webroboter

 

Die folgende UWP Anwendung stellt eine Webroboter dar, welcher eine komplette Web-Domäne einliest nach einzelnen Webseiten und diese Webseiten aktualisiert.

UWP Universal Windows App mit Windows 10 Core

SQLite Datenbank, portable locale Datenbank zur Laufzeit

Scrape_all_Details();

Die Methode Scape All Lists scant alle Listen einträge einer Webseite.

Normalerweise besitzen Webseiten eine Hauptliste oder Übersicht über Ergebnisse. Diese werden mit Scape All Lists eingelesen.

Wenn die Liste auf mehrere Seiten mit Pages verteilt ist, werden alle Pages einzeln als Liste durchgeblätter

Scrape_all_Details();

 

Scrape_all_Details()

Mit Scape All Details warden alle gesammelten Webseiten gelesen oder aktualisiert. Jeder Datensatz hat einen Zeitstempel, welcher die Aktualisierung festhält

Scrape_all_Details()

 

db_Update_Add_ListRecord

In Update Add ListRecord wird eine URL in die Datenbank-Tabelle hinzugefĂźgt oder falls dieser Eintrag schon besteht aktualisiert

db_Update_Add_ListRecord(string sURL, string sTitle)

 

using System;

using System.Collections.Generic;

using System.IO;

using System.Linq;

using System.Runtime.InteropServices.WindowsRuntime;

using Windows.Foundation;

using Windows.Foundation.Collections;

using Windows.UI.Xaml;

using Windows.UI.Xaml.Controls;

using Windows.UI.Xaml.Controls.Primitives;

using Windows.UI.Xaml.Data;

using Windows.UI.Xaml.Input;

using Windows.UI.Xaml.Media;

using Windows.UI.Xaml.Navigation;

 

//< using >

using HtmlAgilityPack;          //HtmlDocument

using System.Net;               //*WebRequest

using System.Threading.Tasks;   //*Task

using Microsoft.Data.Sqlite;    //*SQLite for UWP from Microsoft

//</ using >

 

namespace robot_ComputerFutures

{

    /// <summary>

    /// WebRobot reading website

    /// </summary>

    public sealed partial class MainPage : Page

    {

 

        #region Page

        //--------------------< region: Page >---------------------

        public MainPage()

        {

            this.InitializeComponent();

            optStop.IsChecked = false;

            clsDB.db_Create_Tables();

        }

        //--------------------</ region: Page >---------------------

        #endregion /Page

 

 

        #region Buttons

        //--------------------< region: Buttons >---------------------

        private void Button_Start_Click(object sender, RoutedEventArgs e)

        {

            //--------< Button_Start_Click() >--------

            optStop.IsChecked = false;

            Scrape_List(app_settings._url_Startlist);

            //--------</ Button_Start_Click() >--------

        }

 

 

        private void Button_Details_Click(object sender, RoutedEventArgs e)

        {

            //--------< Button_Details_Click() >--------

            optStop.IsChecked = false;

            Scrape_all_Details();

            //--------</ Button_Details_Click() >--------

        }

        //--------------------</ region: Buttons >---------------------

        #endregion /Buttons

 

 

        #region Methods Scan

        //--------------------< region: Methods Scan >---------------------

        private async void Scrape_List(string sURL)

        {

            //--------< Scrape_List() >--------

            Textbox_URL.Text=sURL;

            Uri baseUrl = new Uri(sURL);

 

            if (optStop.IsChecked == truereturn;

 

            string sPage = baseUrl.Query;

            fx_Log("--< " + sPage + " >--");

 

            HtmlDocument doc = await Web_Get_HtmlDocument(sURL);

            if (doc == nullreturn;

 

            //< nodes > 

            HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//li[@class=\"job-result-item\"]"); //*find subnode with //

            //</ nodes > 

 

            //------< @Loop: Detail Nodes >------

            foreach (HtmlNode node in nodes)

            {

                //----< In Detail-Node >----

                if (optStop.IsChecked == truereturn;

 

                HtmlNode nodeTitle = node.SelectSingleNode(".//div[@class=\"job-title\"]"); //*find subnode with .//

                if (nodeTitle != null)

                {

                    //--< get a_href >--

                    HtmlNode node_to_Detail = nodeTitle.SelectSingleNode("a");

                    string sTitle = node_to_Detail.InnerText;

                    string sURL_Detail_relative = node_to_Detail.GetAttributeValue("href""");

                    string sURL_Detail_absolute = new Uri(baseUrl, sURL_Detail_relative).AbsoluteUri;

 

                    db_Update_Add_ListRecord(sURL_Detail_absolute, sTitle);

 

                    //< print >

                    fx_Log(sTitle);

                    //</ print >

                    //--</ get a_href >--

                }

                //----</ In Detail-Node >----

            }

            //------</ @Loop: Detail Nodes >------

 

            fx_Log("--</ " + sPage + " >--");

            fx_Log("");

 

 

            //--< #Next >--

            HtmlNode nodeGroup_Next = doc.DocumentNode.SelectSingleNode("//span[@class=\"next\"]");

            if (nodeGroup_Next != null)

            {

                HtmlNode node_Next = nodeGroup_Next.SelectSingleNode("a");

                string sURL_Next_relative = node_Next.GetAttributeValue("href""");

                string sURL_Next = new Uri(baseUrl, sURL_Next_relative).AbsoluteUri;

                Textbox_URL.Text = sURL_Next;

                //-< load Next >-

                Scrape_List(sURL_Next);

                //-</ load Next >-

            }

            else

            {

                Textbox_URL.Text = "";

            }

            //--</ #Next >--

            //--------</ Scrape_List() >--------

        }

 

        private void Scrape_all_Details()

        {

            //--------< Scrape_all_Details() >--------

            fx_Log("----< @Read Details >----");

 

            //----< @Loop: Alle Empty Records >----

            while (1 == 1)

            {

                //----< Detail >----

                if (optStop.IsChecked == truereturn;

 

                //< find record >

                string sSQL = "SELECT [IDDetail] FROM tbl_Projects WHERE [dtScan] IS NULL  LIMIT 1";

                SqliteDataReader dataReader= clsDB.Get_DataReader(sSQL);

                //</ find record >

                if (dataReader.HasRows )

                {

                    dataReader.Read();

                    Scrape_Detail_byIDProjekt(Convert.ToInt32(dataReader["IDDetail"]));

                }

                else

                {

                    break;

                }

                //----</ Detail >----

            }

            //----</ @Loop: Alle Empty Records >----

 

            fx_Log("----</ @Read Details >----");

            //--------</ Scrape_all_Details() >--------

        }

 

        private async void Scrape_Detail_byIDProjekt(int ID)

        {

            //--------< Scrape_Detail() >--------

            if (optStop.IsChecked == truereturn;

 

            //fx_Log("--< Read Detail >--");

            fx_Log("Detail=" + ID);

 

            string sURL = clsDB.Get_Value_as_String("URL""tbl_Details""[IDDetail]=" + ID);

            HtmlDocument doc = await Web_Get_HtmlDocument(sURL);

            //< check >

            if (doc == null)

            {

                //< update >

                string sql_Error = "UPDATE tbl_Details SET [dtScan] = CURRENT_TIMESTAMP WHERE IDDetail = " + ID;  //SYSDATETIME()

                clsDB.Execute_SQL(sql_Error);

                //</ update >

                return;

            }

            //</ check >

 

            //----< In Detail-Node >----

            //< Text >

            string sText = "";

            HtmlNode nodeText = doc.DocumentNode.SelectSingleNode("//article[@class=\"clearfix mb30\"]");

            if (nodeText != null) { sText = nodeText.InnerText; }

            //</ Text >

 

            //< Special >

            string sOrt = html_GetText_OuterGroup_by_InnerFilter(doc, "strong""Ort");

            string sGehalt = html_GetText_OuterGroup_by_InnerFilter(doc, "strong""Gehalt");

            string sBereiche = html_GetText_OuterGroup_by_InnerFilter(doc, "strong""Bereiche");

            string sArt = html_GetText_OuterGroup_by_InnerFilter(doc, "strong""Art");

            //</ Special >

 

            //< correct >

            sText = clsCheck.correct_String(sText);

            sOrt = clsCheck.correct_String(sOrt);

            sGehalt = clsCheck.correct_String(sGehalt);

            sBereiche = clsCheck.correct_String(sBereiche);

            sArt = clsCheck.correct_String(sArt);

            //</ correct >

 

 

 

            //< update >

            string sql_Update = "UPDATE tbl_Details ";

            sql_Update += Environment.NewLine + " SET [Text]='" + sText + "',    [dtScan] = CURRENT_TIMESTAMP"//SYSDATETIME()

            sql_Update += Environment.NewLine + " ,[Ort]='" + sOrt + "',[Gehalt]='" + sGehalt + "',[Bereiche]='" + sBereiche + "',[Art]='" + sArt + "'";

            sql_Update += " WHERE IDDetail = " + ID;

            clsDB.Execute_SQL(sql_Update);

            //</ update >

 

            //----</ In Detail-Node >----

 

            //fx_Log("--</ Read Detail >--");

            fx_Log("/Detail=" + ID);

            //--------</ Scrape_Detail() >--------

        }

        //--------------------< region: Methods Scan >---------------------

        #endregion Methods Scan

 

 

 

        #region Methods HTML

        //--------------------< region: Methods >---------------------

        private async Task<HtmlDocument> Web_Get_HtmlDocument(string sURL)

        {

            //------------< fx_read_Page() >------------

            //* get the HTML Document of a website-URL      

            try

            {

                //-< init >-

                //< WebRequest and Response >

                WebRequest objRequest = WebRequest.Create(sURL);

                WebResponse objResponse = await objRequest.GetResponseAsync();

                //</ WebRequest and Response >

 

                //< Stream and Reader >

                Stream objDataStream = objResponse.GetResponseStream();

                StreamReader TextReader = new StreamReader(objDataStream);

                //</ Stream and Reader >

                //-</ init >-

 

                //< download >

                //* Read Website to local String

                string sHTML = TextReader.ReadToEnd();

                //</ download >

 

                //< get HTMLdocument >

                //*create and load to local HtmlDocument

                HtmlDocument doc = new HtmlDocument();

                doc.LoadHtml(sHTML);

                //</ get HTMLdocument >

 

                //< output >

                return doc;

                //</ output >

            }

            catch (Exception)

            {

                return null;

            }

 

            //------------</ fx_read_Page() >------------

        }

 

        private string html_GetText_OuterGroup_by_InnerFilter(HtmlDocument doc, string par_Html_Element_Type, string sFilter_Inner)

        {

            string sReturn = "";

 

            HtmlNode node_Inner = doc.DocumentNode.SelectSingleNode("//" + par_Html_Element_Type + "[text() = '" + sFilter_Inner + "']");

            if (node_Inner != null)

            {

                HtmlNode parent = node_Inner.ParentNode;

                node_Inner.Remove();

                sReturn = parent.InnerText;

                sReturn.Trim();

                sReturn.TrimStart();

            }

            return sReturn;

        }

        //--------------------</ region: Methods >---------------------

        #endregion /Methods Html

 

 

 

        #region Methods Data

        //--------------------< region: Methods Data >---------------------

        

 

        private void db_Update_Add_ListRecord(string sURL, string sTitle)

        {

            //--------< db_Update_Add_Record() >--------

            //*Update or add Record

            //< correct>

            sURL = sURL.Replace("'""''");

            sTitle = sTitle.Replace("'""''");

            //</ correct>

 

            //< find record >

            string sSQL = "SELECT * FROM tbl_Details WHERE [URL] = '" + sURL + "' LIMIT 1";

            SqliteDataReader dataReader=clsDB.Get_DataReader(sSQL ) ;           

            if (dataReader.HasRows==false )

            {

                //< add >

                string sql_Add = "INSERT INTO tbl_Details ([URL],[Title],[dtList]) VALUES('" + sURL + "','" + sTitle + "', CURRENT_TIMESTAMP)"//SYSDATETIME

                clsDB.Execute_SQL(sql_Add);

                //</ add >

            }

            else

            {

                //< update >

                string IDDetail = dataReader["IDDetail"].ToString();

                string sql_Update = "UPDATE tbl_Details SET [dtList] = CURRENT_TIMESTAMP WHERE IDDetail = " + IDDetail;  //SYSDATETIME()

                clsDB.Execute_SQL(sql_Update);

            }

                

            //--------</ db_Update_Add_Record() >--------

        }

 

        //--------------------</ region: Methods Data >---------------------

        #endregion /Methods Data

 

        #region Sys

        //--------------------< region: Sys >---------------------

        public void fx_Log(string sLog)

        {

            //------------< fx_Log() >------------

            //* log Text to Textbox

            string sText = Textbox_Log.Text;

            sText = DateTime.Now + " " + sLog + Environment.NewLine + sText;

            if (sText.Length > 50000) { sText = sText.Substring(50000); }

            Textbox_Log.Text = sText;

            Textbox_Log.UpdateLayout();

            

            //< refresh > 

            

            //</ refresh > 

            //------------</ fx_Log() >------------

        }

 

        //--------------------</ region: Sys >---------------------

        #endregion /Sys

 

    }

 

}

Hilfsklasse: clsDB.cs

In der clsDB werden alle Datenbank-Arbeiten zur Anwendung ausgefĂźhrt.

Im wesentliche gibt es

das Aufbauen einer SQLite Datenbank Verbindung

SqliteConnection Get_Sqlite_Connection()

 

Das Erstellen der Datenbank mit Tabellen falls diese nicht besteht

async Task<bool>  db_Create_Tables()

 

 SELECT Befehle als Reader, ähnlich einer DataTable

SqliteDataReader Get_DataReader(string SQL_Text)

 

 COMMAND Befehle Update und Insert

Execute_SQL(string SQL_Text)

 

 Und die beliebte Methode zum ermitteln eines einzelnen Wertes

Get_Value_as_String(string sField, string sTable, string sWhere)

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

//< add using >

using System.Data.SqlClient;    //*local DB

using System.Data;              //*ConnectionState, DataTable

using Microsoft.Data.Sqlite;

using Windows.UI.Popups;

//</ add using >

 

 

public static class clsDB

{

    //-------------------< Class: DB >-------------------

 

    public static SqliteConnection sqlite_Connection = null;

 

    public static async Task<bool>  db_Create_Tables()

    {

        //--------< db_Create_Tables() >--------

        //SqliteEngine.UseWinSqlite3(); //Configuring library to use SDK version of SQLite

        SqliteConnection cn_connection = Get_Sqlite_Connection();

        String tableCommand = "CREATE TABLE IF NOT EXISTS " + 

                "tbl_Details " +

                "( " +

                "[IDDetail] INTEGER PRIMARY KEY AUTOINCREMENT, " +

                "[URL] NVARCHAR(500) NULL ," +

                "[Title] NVARCHAR(255) NULL, " +

                "[Text] NVARCHAR(10000) NULL,  " +

                "[dtScan] DATETIME NULL,   " +

                "[Ort]    NVARCHAR(255) NULL, " +

                "[Bereiche] NVARCHAR(255) NULL, " +

                "[Gehalt] NVARCHAR(255) NULL, " +

                "[Art] NVARCHAR(255) NULL," +

                "[dtList] DATETIME NULL" +

                ")";

            //"[IDDetail] INT            IDENTITY (1, 1) NOT NULL,

            SqliteCommand createTable = new SqliteCommand(tableCommand, cn_connection);

            try

            {

                createTable.ExecuteReader();

                return true;

            }

            catch (SqliteException ex )

            {

                show_Message(ex.Message.ToString());

                return false;

            }

            //--------</ db_Create_Tables() >--------

        

    }

 

 

 

    public static SqliteConnection Get_Sqlite_Connection()

    {

        //--------< db_Get_Connection() >--------

        //< db oeffnen >

        SqliteConnection cn_connection = new SqliteConnection(app_settings._sqlite_string);

        if (cn_connection.State != ConnectionState.Open) cn_connection.Open();

        //</ db oeffnen >

 

        //< output >

        return cn_connection;

        //</ output >

        //--------</ db_Get_Connection() >--------

    }

 

    public static SqliteDataReader Get_DataReader(string SQL_Text)

    {

        //--------< db_Get_DataTable() >--------

        SqliteConnection cn_connection = Get_Sqlite_Connection();

 

        //< get Table >

        SqliteCommand selectCommand = new SqliteCommand(SQL_Text, cn_connection);

        SqliteDataReader query;

        try

        {

            query = selectCommand.ExecuteReader();

        }

        catch (SqliteException ex)

        {

            show_Message(ex.Message);

            return null;

        }        

        //</ get Table >

 

        //< output >

        return query;

        //</ output >

        //--------</ db_Get_DataTable() >--------

    }

 

    public static string Get_Value_as_String(string sField, string sTable, string sWhere)

    {

        //--------< Get_Value_as_String() >--------

 

        string sReturn = "";

        string SQL_Text = "SELECT [" + sField + "] FROM " + sTable + " WHERE " + sWhere + " LIMIT 1";

 

 

        //< get Table >

        SqliteDataReader reader = Get_DataReader(SQL_Text);

        if (reader.HasRows)

        {

            reader.Read();

            sReturn = reader[sField].ToString();

        }

 

        //< output >

        return sReturn;

        //</ output >

        //--------</ Get_Value_as_String() >--------

 

    }

 

    public static void Execute_SQL(string SQL_Text)

    {

        //--------< Execute_SQL() >--------

        //< check >

        SqliteConnection cn_connection = Get_Sqlite_Connection();

        //</ check >

 

        SqliteCommand cmdUpdate = new SqliteCommand(SQL_Text, cn_connection);

        try

        {

            cmdUpdate.ExecuteReader();

        }

        catch (SqliteException ex)

        {

            show_Message(ex.Message);

            return;

        }

        //</ update >

        //--------</ Execute_SQL() >--------

    }

 

    public static void Close_DB_Connection()

    {

        //--------< Close_DB_Connection() >--------

        //< db oeffnen >

        sqlite_Connection.Close();

        //</ db oeffnen >

 

        //--------</ Close_DB_Connection() >--------

    }

 

 

 

    public async static void show_Message(string sMessage)

    {

        MessageDialog dialog = new MessageDialog(sMessage, "Information");

        await dialog.ShowAsync();

    }

    //-------------------</ Class: DB >-------------------

}

Hilfsklasse: app_Settings.cs

Die Settings sind in dieser UWP App direkt fest codiert.

Diese befinden sich einfachheitshalber in der app_settings.cs Klasse

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

 

    public static class app_settings

    {

        public static string _Username = "address@email.de";

        public static string _Password = "0123456789";

 

        public static string _sqlite_string = "Filename=sqliteSample.db";

        public static string _url_Startlist = "https://testsite.com";

    }