需要在C#控制台中从源代码中提取特定的URL

时间:2018-07-18 11:48:06

标签: c#

我正在制作一个机器人,该机器人需要显示用户提供的页面链接中的图像。我看到的唯一方法是从源代码中获取href代码

using (WebClient client = new WebClient())
            {
                string htmlCode = client.DownloadString("url that is input by the user");
                Console.WriteLine(htmlCode);
                Console.ReadKey();
            }

是获取网址的当前代码。如果有帮助,此查询将目标锁定在Duelmaster Wiki上的卡片页面,因此页面布局相同。我想我想问的是如何从整个源代码文件中获取该代码?

1 个答案:

答案 0 :(得分:0)

您可以使用正则表达式从字符串中提取href数据

正则表达式:-

  

href [\ s] = [\ s] \“(。?)[\ s] \”

C#代码

包含命名空间

using System.Text.RegularExpressions;

更新代码

static void Main()
{
    Console.WriteLine("Enter Url you want to Extract data from");
    string userInput = Console.ReadLine();
    Task t = new Task(DownloadPageAsync);
    t.Start();
    Console.WriteLine("Downloading page...");
    Console.ReadLine();
}

static async void DownloadPageAsync(string requestUrl)
{
    // ... Use HttpClient instead of webclient
    using (HttpClient client = new HttpClient())
    using (HttpResponseMessage response = await client.GetAsync(requestUrl))
    using (HttpContent content = response.Content)
    {
        string mydata = await content.ReadAsStringAsync();
        Regex regex = new Regex("href[\\s]*=[\\s]*\"(.*?)[\\s]*\\\"");
        foreach (Match htmlPath in regex.Matches(mydata))
        {
            // Here you can write your custom logic
            Console.WriteLine(htmlPath.Groups[1].Value);
        }
    }
}

代码说明

Regex regex = new Regex("href[\\s]*=[\\s]*\"(.*?)[\\s]*\\\"");

此行将使用给定的正则表达式创建regex对象

发布正则表达式后,您可以找到正则表达式说明Here

foreach (Match htmlPath in regex.Matches(mydata))
{

此行将遍历给定字符串中使用正则表达式找到的所有匹配项。

Console.WriteLine(htmlPath.Groups[1].Value);

正则表达式捕获组中的通知(。*?)

上一行会在href括号内的案例数据中为您提供该组中的包含对象

相关问题