c# HTML ile XPath kontrolü ve değer döndürme


Özet:

  • XPath kullanarak belirli öğeleri, class, id, metin içerikleri gibi özelliklerle seçebilirsiniz.
  • Tarayıcıdaki Geliştirici Araçları ile HTML yapısını inceleyip XPath ifadesini test edebilirsiniz.
  • HtmlAgilityPack kullanarak, XPath ile öğeleri seçip veriyi çekebilirsiniz.

XPath ve class ile element tespiti, HTML belge yapısını anlamak ve doğru şekilde erişim sağlamak için önemli becerilerdir. Bu konuyu adım adım açıklayarak öğretmeye çalışacağım.

1. HTML ve XPath Nedir?

HTML:

HTML (HyperText Markup Language), web sayfalarını oluşturan etiketlerin dilidir. Web sayfasındaki her içerik bir HTML etiketiyle temsil edilir. Örneğin, şu HTML etiketi bir öğe içerir:

html
<div class="product-info">Ürün Adı</div>

Burada:

  • <div>: HTML öğesinin türü.
  • class="product-info": div öğesinin class (sınıf) özelliği.
  • "Ürün Adı": Öğenin içeriği.

XPath:

XPath (XML Path Language), XML veya HTML belgesindeki öğelere ulaşmak için kullanılan bir dil ve ifade biçimidir. XPath, belgedeki öğeleri seçmek için belirli yolları belirtir.

2. HTML İçeriğini İncelemek

Öncelikle, sayfadaki öğeleri tespit etmek için tarayıcıda Geliştirici Araçlarını (DevTools) kullanabilirsiniz. Bu araçları kullanarak sayfanın yapısını görebilir, hangi öğe ile çalıştığınızı belirleyebilirsiniz.

Adımlar:

  1. Chrome'da Geliştirici Araçlarını Açma:
    • Sağ tıklayın ve İncele seçeneğine tıklayın.
    • Alternatif olarak, F12 tuşuna basabilirsiniz.
  2. Öğeyi Seçmek:
    • Elements sekmesinde sayfanın HTML yapısını görüyorsunuz.
    • Sağ tıklayıp İncele dediğinizde öğenin HTML kodunu da görebilirsiniz.

3. XPath ile Öğeleri Seçme

XPath, bir HTML veya XML belgesinde belirli öğelere ulaşmanıza olanak sağlar. XPath'in doğru çalışabilmesi için öğeleri doğru biçimde tanımlamanız gerekir.

Örnek HTML Yapısı:

Örneğin aşağıdaki HTML yapısına sahip bir ürün sayfasını düşünelim:

html
<div class="product"> <h1 class="product-title">Ürün Adı</h1> <span class="product-price">200 TL</span> <div class="product-description">Açıklama metni...</div> </div>

Bu yapıda:

  • product sınıfına sahip bir <div> öğesi var.
  • İçinde bir <h1> (başlık), bir <span> (fiyat) ve bir <div> (açıklama) öğesi var.

4. XPath İfadesi Yazmak

Aşağıda örnekleri verilen XPath ifadeleri, belirli öğeleri seçmek için kullanılır.

XPath İfadesi:

  1. Bir öğeyi class ile seçmek: Eğer bir öğenin class özelliği ile seçim yapacaksanız, aşağıdaki gibi bir XPath kullanabilirsiniz:

    xpath
    //div[@class='product']

    Bu XPath, class="product" olan tüm <div> öğelerini seçer.

  2. Alt öğeleri seçmek: Eğer iç içe öğelere erişmek istiyorsanız, XPath'i şu şekilde kullanabilirsiniz:

    xpath
    //div[@class='product']//span[@class='product-price']

    Bu ifade, class="product" olan bir <div> öğesinin içinde, class="product-price" olan ilk <span> öğesini seçer.

  3. Belirli bir öğeyi seçmek (Index kullanma): Eğer öğe sayısı birden fazlaysa ve belirli bir öğeye ulaşmak istiyorsanız, öğe sırasını (index) kullanabilirsiniz:

    xpath
    //div[@class='product']/h1

    Bu, class="product" olan <div> öğesinin içindeki ilk <h1> öğesini seçer.

  4. Metin içeren öğeleri seçmek: Eğer öğede belirli bir metin varsa, bunu şu şekilde seçebilirsiniz:

    xpath
    //span[contains(text(), '200 TL')]

    Bu, 200 TL metnini içeren ilk <span> öğesini seçecektir.

5. XPath ve class ile Öğeleri Seçme

Örneğin, bir sayfada stok bilgisini çekmek istiyorsanız ve stok bilgisi şu şekilde bir yapıda ise:

html
<div class="product"> <span class="stock-status">Stokta Var</span> </div>

Burada, stock-status class'ına sahip olan <span> öğesini seçmek için XPath şu şekilde olacak:

xpath
//span[@class='stock-status']

Bu, class="stock-status" olan <span> öğesini seçecektir.

6. Pratik Örnek - C# ve HtmlAgilityPack ile XPath Kullanmak

Şimdi, öğrendiğiniz XPath'i C# uygulamasında nasıl kullanabileceğinizi adım adım görelim.

Örnek C# Kodu:

  1. NuGet Paketini Yükleme:

    • HtmlAgilityPack kütüphanesini NuGet üzerinden yüklemeniz gerekecek.
    bash
    Install-Package HtmlAgilityPack
  2. HTML İçeriğini Çekme ve XPath Kullanma:

    csharp
    using HtmlAgilityPack; using System; using System.Net.Http; using System.Threading.Tasks; public class StockChecker { public static async Task Main(string[] args) { string url = "https://www.ornek-site.com/urun"; // Ürün sayfası linki var stockStatus = await GetStockStatus(url); Console.WriteLine("Stok Durumu: " + stockStatus); } public static async Task<string> GetStockStatus(string url) { try { using (HttpClient client = new HttpClient()) { HttpResponseMessage response = await client.GetAsync(url); response.EnsureSuccessStatusCode(); string htmlContent = await response.Content.ReadAsStringAsync(); // HtmlAgilityPack ile HTML içeriği yükleme HtmlDocument doc = new HtmlDocument(); doc.LoadHtml(htmlContent); // XPath ile stok bilgisini alma var stockNode = doc.DocumentNode.SelectSingleNode("//span[@class='stock-status']"); if (stockNode != null) { return stockNode.InnerText.Trim(); // Stok bilgisini döndür } else { return "Stok bilgisi bulunamadı."; } } } catch (Exception ex) { return $"Hata: {ex.Message}"; } } }

7. Test Etme

Yukarıdaki kodu çalıştırarak, doğru HTML öğesine erişip stok bilgisini çekmeye çalışabilirsiniz. Eğer XPath doğruysa, doğru öğeyi seçecek ve stok bilgisini döndürecektir.


Program Kodu:
 
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using HtmlAgilityPack;
using HtmlDocument = HtmlAgilityPack.HtmlDocument;


namespace StokKontrol
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        // Button click event to start the stock check process
        private async void btnCheckStock_Click_1(object sender, EventArgs e)
        {
            // Get the product link from the textbox
            string productLink = txtProductLink.Text.Trim();

            // Validate the URL
            if (string.IsNullOrEmpty(productLink))
            {
                MessageBox.Show("Lütfen geçerli bir ürün linki girin.");
                return;
            }

            // Get stock info by calling the method asynchronously
            string stockStatus = await GetStockInfoAsync(productLink);

            // Display the result in the label
            lblStockStatus.Text = stockStatus;
        }

        // Method to get stock info from the website
        private async Task<string> GetStockInfoAsync(string url)
        {
            try
            {
                // Create a new HttpClient instance
                using (HttpClient client = new HttpClient())
                {
                    // Send a GET request to the product page
                    HttpResponseMessage response = await client.GetAsync(url);
                    response.EnsureSuccessStatusCode();

                    // Read the HTML content from the response
                    string htmlContent = await response.Content.ReadAsStringAsync();

                    // Load the HTML content into HtmlAgilityPack
                    HtmlDocument doc = new HtmlDocument();
                    doc.LoadHtml(htmlContent);

                    // Assuming the stock information is inside a specific HTML element (you need to change this to match the target site)
                    var stockNode = doc.DocumentNode.SelectSingleNode("//li[contains(text(), 'Stok:')]");

                    if (stockNode != null)
                    {
                        // If stock information is found, return it
                        return stockNode.InnerText.Trim();
                     
                    }
                    else
                    {
                        // If stock information is not found, return a default message
                        return "Stok bilgisi bulunamadı.";
                    }
                }
            }
            catch (Exception ex)
            {
                // Handle any exceptions, e.g. network errors or parsing issues
                return $"Hata: {ex.Message}";
            }
        }

      
    }
}

Yorum Gönder

0 Yorumlar