我想下载HTML源代码并从中提取内容,但是Webclient只下载一次, 第二次它不起作用,直到我退出程序并再次重新启动它。
这是下载功能,我在一个按钮中调用了它:
public static async Task DownF(string[] Urls)
{
WebClient KeyClient = new WebClient();
try
{
await Task.Run(() =>
{
const string pattern = "<span.*?>(.*?)<\\/span>";
for (int i = 0; i < 3; i++)
{
while (KeyClient.IsBusy)
{
System.Threading.Thread.Sleep(1000);
}
string page = KeyClient.DownloadString(Urls[i]);
MatchCollection matchs = Regex.Matches(page, pattern);
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
if (matchs.Count > 0)
{
StreamWriter wrt = new StreamWriter(path + "\\results.txt");
int KeyWordCounter = 0;
foreach (Match m in matchs)
{
KeyWordCounter += 1;
wrt.WriteLine(KeyWordCounter + "-" + m.Groups[1].Value);
}
wrt.Close();
}
}
MessageBox.Show("finich!");
});
}
catch(Exception e)
{
MessageBox.Show(e.Message);
}
// *********按钮中的呼叫功能
string site1 = "www.site1.com";
string site2 = "www.site2.com";
string site3 = "www.site3.com";
string [] Urls = new string[3];
Urls[0] = site1;
Urls[1] = site2;
Urls[2] = site3;
DownF(Urls);
我同意@ D.Foley。您可以通过NuGet安装WebDriver,它将为您提供所需的所有功能。这是一个非常酷的程序包,它允许您从浏览器通过多种方式提取数据。它具有诸如getByXPath(),getByCssSelector()等之类的功能。此外,它还为您提供了快速轻松地浏览网站的机会。
我知道它不能完全回答问题,但是您会尝试使用Web客户端和正则表达式来抓取内容,从而使自己的生活变得艰难。我也曾经犯过这个错误。
为什么不使用IronWebScraper之类的工具或其他专门用于抓取网页的库。使用正则表达式不是正确的解决方法。