找回密码
 FreeOZ用户注册
查看: 1129|回复: 0
打印 上一主题 下一主题

[学习深造] The source code I wrote to grab all javascript of a webpage and save to files

[复制链接]
跳转到指定楼层
1#
发表于 29-10-2013 06:34:23 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有帐号?FreeOZ用户注册

x
本帖最后由 DDD888 于 29-10-2013 08:10 编辑

It is quite labour intensive to save each javascript file by browser and I thought to auto save all javascript files.

It is c# source code.

It use HtmlAgilityPack package to do the html job.

It only save the javascript belongs to the domain. It won't save other website i.e. google statics javascript

Modify it to suit your needs.


namespace GrabWebsiteJavascript
{
    using System;
    using System.IO;
    using System.Net;
    using System.Threading.Tasks;

    using HtmlAgilityPack;

    public sealed class Job
    {
        private readonly string url;
        private readonly string folder;
        private readonly string domain;

        public Job(string aUrl, string aFolder)
        {
            url = aUrl;
            folder = aFolder;
            var index = aUrl.IndexOf('#');
            domain = aUrl.Substring(0, index - 1);
        }

        public async Task Execute()
        {
            var html = await new WebClient().DownloadStringTaskAsync(url);
            var page = new HtmlDocument { OptionAutoCloseOnEnd = false, OptionFixNestedTags = true };
            page.LoadHtml(html);
            //var page = new HtmlWeb().Load(url);
            var index = 0;

            foreach (var node in page.DocumentNode.SelectNodes("//script"))
            {
                var innerHtml = node.InnerHtml;
                if (string.IsNullOrEmpty(innerHtml))
                {
                    var filePath = node.Attributes["src"].Value;
                    if (filePath.StartsWith("http"))
                    {
                        continue;
                    }

                    var position = filePath.IndexOf('?');
                    if (-1 != position)
                    {
                        var filePathCleaned = filePath.Substring(0, position);
                        var fullUrl = domain + filePathCleaned;
                        var fileName = Path.GetFileName(filePathCleaned);
                        var webClient = new WebClient();
                        var varUri = new Uri(fullUrl);
                        webClient.DownloadFile(varUri, folder + "\\" + fileName);
                    }
                }
                else
                {
                    File.WriteAllText(folder + "\\javascript" + index.ToString() + ".js", innerHtml);
                    index++;
                }
            }
        }
    }
}
回复  

使用道具 举报

您需要登录后才可以回帖 登录 | FreeOZ用户注册

本版积分规则

小黑屋|手机版|Archiver|FreeOZ论坛

GMT+10, 12-8-2026 15:32 , Processed in 0.027117 second(s), 17 queries , Gzip On, Redis On.

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表