【发布时间】:2013-12-30 18:00:43
【问题描述】:
所以,我正在编写一个 C# WinForms 应用程序来从 4chan 获取图像。
最近,图片已经托管在另一个域上,所以我一直在尝试使用RegEx从boards.4chan.org域中扫描一个线程的html代码,并使用它在i.4cdn.org域上找到相应的图像。现在存储。我这样做是为了下载单个线程而不是整个板。
private void DownloadImages(string saveDir, string board, string threadNum, string fileType)
{
string htmlString;
int imageNum = 0;
WebClient wc = new WebClient();
try
{
htmlString = wc.DownloadString("http://boards.4chan.org/" + board + "/res/" + threadNum);
}
catch(Exception ex)
{
txtOutput.Text = ex.ToString();
return;
}
txtOutput.Text = "Found thread!";
MatchCollection allMatchResults;
Regex regexObj = new Regex("//i.4cdn.org/" + board + "/src/*." + fileType,RegexOptions.Singleline);
allMatchResults = regexObj.Matches(htmlString);
foreach(Match match in allMatchResults)
{
txtOutput.Text = match.ToString();
try
{
//txtOutput.Text = "Downloading file ";
wc.DownloadFile("http:" + match.Value.ToString() + "." + fileType, saveDir + imageNum + "." + fileType);
Thread.Sleep(1000);
imageNum++;
}
catch (Exception x)
{
txtOutput.Text = x.ToString();
return;
}
}
}
现在,我已经有一段时间没有使用 RegEx 了,过去也没有在 C# 中使用过它,所以我不确定我做的是否完全错误。我试图让它解析htmlString 以查找与//i.4cdn.org url 的任何匹配项,同时传递板和文件类型(为了具体起见,它们来自表单上的checkedListBoxes)。
我让它将网页的源代码抓取到一个字符串中,这样我就可以解析它并查找图像 url,然后我可以在 4cdn 域上找到相应的图像。
我的问题是,虽然我收到了“找到线程”的消息,但程序似乎永远不会超过那个点——它似乎永远不会进入foreach 循环。
如果有更好的方法可以做到这一点,我愿意接受建议。我已阅读不要尝试使用 RegEx 解析 html。但我认为我在这里会很好,因为它不是我正在寻找的 html 本身。
【问题讨论】: