如何在 c# (Azure Functions) 中下载整个网站
How to Download entire website in c# (Azure Functions)
我正在开发一个爬虫,我需要保存一些爬虫成功的证据。
我正在寻找一种方法来下载已发送 URL 的所有 HTML、CSS 和 JS,并创建与目标站点相同的文件夹结构。
我将不得不使用 Azure Functions 来做爬虫。
我的想法是创建一个站点,下载内容并保存在 Azure Blob 中。
我找到了 this article,但它只显示了如何下载 HTML,我需要创建与爬虫看到的完全相同的东西(带图像,CSS 并处理了 JS)。
我相信所有绝对路径都可以,真正的问题是我将创建文件夹来保存文件的相对路径。
有人可以帮助我吗?
嗯,相信这个回答能对和我有同样经历的人有所帮助。
我的解决方案是下载 HTML(使用 HttpWebRequest)并写入文件(存储在 Azure Blob 中)。
在我的例子中,我做了一个函数来更正HTML文件中的所有亲属路径,如下所示:
private static HtmlDocument CorrectHTMLReferencies(string urlRoot, string htmlContent)
{
HtmlDocument document = new HtmlDocument();
document.LoadHtml(htmlContent);
Regex rx = new Regex(@"([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?");
var nodesIMG = document.DocumentNode.SelectNodes("//img");
var nodesCSS = document.DocumentNode.SelectNodes("//link");
var nodesJS = document.DocumentNode.SelectNodes("//script");
string protocol = "http:";
if (urlRoot.Contains(":"))
protocol = urlRoot.Split(':')[0] + ":";
void WatchURl(HtmlNodeCollection colNodes, string attr)
{
foreach (HtmlNode node in colNodes)
{
if (node.Attributes.Any(a => a.Name?.ToLower() == attr.ToLower()))
{
string link = node.Attributes[attr].Value;
if (rx.IsMatch(link))
{
if (link.Substring(0, 2) == "//")
{
string novaUrl = protocol + link;
node.SetAttributeValue(attr, novaUrl);
}
}
else
{
node.SetAttributeValue(attr, urlRoot + link);
}
}
}
}
WatchURl(nodesIMG, "src");
WatchURl(nodesCSS, "href");
WatchURl(nodesJS, "src");
return document;
}
我没有下载所有网站,而是只下载了一个文件。
这个对我有用)
;)
我正在开发一个爬虫,我需要保存一些爬虫成功的证据。
我正在寻找一种方法来下载已发送 URL 的所有 HTML、CSS 和 JS,并创建与目标站点相同的文件夹结构。
我将不得不使用 Azure Functions 来做爬虫。
我的想法是创建一个站点,下载内容并保存在 Azure Blob 中。
我找到了 this article,但它只显示了如何下载 HTML,我需要创建与爬虫看到的完全相同的东西(带图像,CSS 并处理了 JS)。
我相信所有绝对路径都可以,真正的问题是我将创建文件夹来保存文件的相对路径。
有人可以帮助我吗?
嗯,相信这个回答能对和我有同样经历的人有所帮助。
我的解决方案是下载 HTML(使用 HttpWebRequest)并写入文件(存储在 Azure Blob 中)。
在我的例子中,我做了一个函数来更正HTML文件中的所有亲属路径,如下所示:
private static HtmlDocument CorrectHTMLReferencies(string urlRoot, string htmlContent)
{
HtmlDocument document = new HtmlDocument();
document.LoadHtml(htmlContent);
Regex rx = new Regex(@"([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?");
var nodesIMG = document.DocumentNode.SelectNodes("//img");
var nodesCSS = document.DocumentNode.SelectNodes("//link");
var nodesJS = document.DocumentNode.SelectNodes("//script");
string protocol = "http:";
if (urlRoot.Contains(":"))
protocol = urlRoot.Split(':')[0] + ":";
void WatchURl(HtmlNodeCollection colNodes, string attr)
{
foreach (HtmlNode node in colNodes)
{
if (node.Attributes.Any(a => a.Name?.ToLower() == attr.ToLower()))
{
string link = node.Attributes[attr].Value;
if (rx.IsMatch(link))
{
if (link.Substring(0, 2) == "//")
{
string novaUrl = protocol + link;
node.SetAttributeValue(attr, novaUrl);
}
}
else
{
node.SetAttributeValue(attr, urlRoot + link);
}
}
}
}
WatchURl(nodesIMG, "src");
WatchURl(nodesCSS, "href");
WatchURl(nodesJS, "src");
return document;
}
我没有下载所有网站,而是只下载了一个文件。 这个对我有用) ;)