簡體   English   中英

WPF C#-從頁面獲取鏈接

[英]WPF C# - taking links from page

我想獲取網頁的源(HTML)代碼,然后在我的WPF中,使用ItemsControl,我只想從該html文檔中獲取鏈接。 例如,作為網址的www.google.com/search?q=stackoverflow,我想從其html代碼中獲取所有主要鏈接。 我是關於C#的入門者,而我正在尋找的關於此問題的內容,我不太了解,這就是為什么我求你讓我詳細介紹一下。 拜托我需要你的幫忙。 謝謝。

您應該檢出HtmlAgilityPack庫,它將幫助您獲取和過濾HTML文檔中的鏈接:

這是一個敏捷的HTML解析器,它構建了一個讀/寫DOM並支持純XPATH或XSLT(您實際上不必了解XPATH或XSLT來使用它,不用擔心...)。 這是一個.NET代碼庫,可讓您解析“網絡外” HTML文件。 該解析器對“真實世界”格式的HTML十分寬容。

一旦使用HtmlAgilityPack從HTML文檔中檢索了所有鏈接,就可以簡單地將返回的鏈接集合綁定(或將其轉換為適合您需求的東西)綁定到ItemsSource並按所需方式顯示它們。

您會在網上找到很多不同的教程,其中有兩個(不要忘記安裝HtmlAgilityPack並在CS文件中定義適當的名稱空間),對於安裝nuget而言,最好的方法是使用nuget,因為它在codeplex項目頁面 ):

這是一個示例,您可以用來將所有鏈接URL放入單個列表框中,並假設所有內容都已放置在Window代碼的后面(我們在這里關注的是HtmlAgilityPack和WPF,而不是體系結構或設計問題^^)

在您的MainWindow.cs

  • 首先, using HtmlAgilityPack;在您的cs文件頂部定義此名稱空間using HtmlAgilityPack;
  • 聲明一個List<string>依賴項屬性,該屬性將是包含所有顯示的鏈接並綁定到Listbox ItemsSourceListbox
  • 然后為您的按鈕聲明Click事件回調,以觸發HTML解析
  • 然后聲明您的回調中正在調用GetLinks方法

這是完整的代碼:

public partial class MainWindow : Window
{
    public List<string> Links
    {
        get { return (List<string>)GetValue(LinksProperty); }
        set { SetValue(LinksProperty, value); }
    }

    // Using a DependencyProperty as the backing store for Links.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty LinksProperty =
        DependencyProperty.Register("Links", typeof(List<string>), typeof(MainWindow), new PropertyMetadata(0));

    public MainWindow()
    {
        InitializeComponent();
        DataContext = this;
    }

    private List<string> GetLinks()
    {
        var links = new List<string>();
        HtmlDocument doc = new HtmlDocument();
        doc.Load("YourHtmlFileInHere");
        foreach (HtmlNode link in doc.DocumentNode.SelectNodes("//a[@href]"))
        {
            HtmlAttribute attribute = link.Attributes["href"];
            if (attribute != null)
            {
                links.Add(attribute.Value);
            }
        }
        return links;
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        this.Links = this.GetLinks();
    }
}

最后,您可以創建一個ListBox和一個Button來顯示進入主Window鏈接列表:

<Window x:Class="WpfApplication2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"></RowDefinition>
            <RowDefinition Height="Auto"></RowDefinition>
        </Grid.RowDefinitions>
        <ListBox Grid.Row="0"  ItemsSource="{Binding Path=Links}"></ListBox>
        <Button Grid.Row="1" Content="Get links" Click="Button_Click"></Button>
    </Grid>
</Window>

當然,這是一個非常基本的示例,“ Links列表內容無法更新,使用這種方式的代碼並不是最好的方法。 但這仍然是一個開始!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM