Advertisement
Guest User

SosachContentParser

a guest
Oct 15th, 2016
264
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.02 KB | None | 0 0
  1. using System;
  2. using System.IO;
  3. using System.Linq;
  4. using System.Net.Http;
  5. using HtmlAgilityPack;
  6. using System.Threading;
  7.  
  8. namespace SosachContentParser
  9. {
  10.     public class Program
  11.     {
  12.         const string XPATH_TO_LINK = "//*[contains(@id, post-body)]/div[2]/figure/figcaption/a";
  13.  
  14.         public static void Main(string[] args)
  15.         {
  16.  
  17.             var threadUrl = args[0];
  18.             var board = threadUrl.Split('/')[3];
  19.             var contentFilesPath = args[1];
  20.  
  21.             string rawHtml;
  22.             using (var client = new HttpClient())
  23.             {
  24.                 rawHtml = client
  25.                     .GetAsync(threadUrl)
  26.                     .Result
  27.                     .Content
  28.                     .ReadAsStringAsync()
  29.                     .Result;
  30.             }
  31.  
  32.             var htmlDoc = new HtmlDocument();
  33.             htmlDoc.LoadHtml(rawHtml);
  34.  
  35.             var links = htmlDoc.DocumentNode
  36.                 .SelectNodes(XPATH_TO_LINK)
  37.                 .Select(x => x.Attributes)
  38.                 .Select(x => x["href"].Value)
  39.                 .Select(x => x.Replace("..", "https://2ch.hk/" + board))
  40.                 .ToList();
  41.  
  42.             Console.WriteLine($"Files count: {links.Count}");
  43.  
  44.             int counter = 0;
  45.             foreach (var link in links.AsParallel())
  46.             {
  47.                 byte[] fileByteArray;
  48.                 using (var client = new HttpClient())
  49.                 {
  50.                     fileByteArray = client
  51.                         .GetAsync(link)
  52.                         .Result
  53.                         .Content
  54.                         .ReadAsByteArrayAsync()
  55.                         .Result;
  56.                 }
  57.  
  58.                 File.WriteAllBytes(contentFilesPath + link.Split('/').Last(), fileByteArray);
  59.  
  60.                 Interlocked.Increment(ref counter);
  61.                 Console.Clear();
  62.                 Console.WriteLine($"Files count: {links.Count}");
  63.                 Console.WriteLine($"Files downloaded: {counter}");
  64.             }
  65.         }
  66.     }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement