Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/33.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在ASP.NET C中读取正则表达式_C#_Asp.net_Regex - Fatal编程技术网

C# 在ASP.NET C中读取正则表达式

C# 在ASP.NET C中读取正则表达式,c#,asp.net,regex,C#,Asp.net,Regex,我能够使用这个正则表达式读取和下载页面上的.jpg文件列表 输出示例:从此行 在html中 问题:我如何读取这种格式的文件 <a href="download/datavoila-setup.exe" id="button_download" title="Download your copy of DataVoila!" onclick="pageTracker._trackPageview('/download/datavoila-setup.exe')"></a>

我能够使用这个正则表达式读取和下载页面上的.jpg文件列表

输出示例:从此行 在html中 问题:我如何读取这种格式的文件

<a href="download/datavoila-setup.exe" id="button_download" title="Download your copy of DataVoila!" onclick="pageTracker._trackPageview('/download/datavoila-setup.exe')"></a>
这是一个倒装回答,它可以工作,但不是我没有得到一个干净的捕获:我认为有一些东西可以编辑分裂的html文本

protected void Button2_Click(object sender, EventArgs e)
        {
            //Get the url given by the user
            string urls;
            urls = txtSiteAddress.Text;
            StringBuilder result = new StringBuilder();

            //Give request to the url given 
            HttpWebRequest requesters = (HttpWebRequest)HttpWebRequest.Create(urls);
            requesters.UserAgent = "";

            //Check for the web response
            WebResponse response = requesters.GetResponse();
            Stream streams = response.GetResponseStream();

            //reads the url as html codes
            StreamReader readers = new StreamReader(streams);
            string htmlTexts = readers.ReadToEnd();

            WebClient webclient = new WebClient();
            string checkurl = webclient.DownloadString(urls);

            List<string> list = new List<string>();//!3

            //Splits the html into with \ into texts
            string[] parts = htmlTexts.Split(new string[] { "\"" },//!3
             StringSplitOptions.RemoveEmptyEntries);//!3

            //Compares the split text with valid file extension
            foreach (string part in parts)//!3
            {
                if (part.EndsWith(".exe"))//!3
                {
                    list.Add(part);//!3

                    //Download the data into a Byte array
                    byte[] fileData = webclient.DownloadData(this.txtSiteAddress.Text + '/' + part);//!6

                    //Create FileStream that will write the byte array to
                    FileStream file =//!6
                            File.Create(this.txtDownloadPath.Text + "\\" + list);//!6

                    //Write the full byte array to the file
                    file.Write(fileData, 0, fileData.Length);//!6

                    //Download message complete
                    lblMessage.Text = "Download Complete!";

                    //Clears the textfields content
                    txtSiteAddress.Text = "";
                    txtDownloadPath.Text = "";

                    //Close the file so other processes can access it
                    file.Close();
                    break;
                }

            }

正则表达式不是解析HTML文件的好选择

HTML不严格,格式也不规则

使用

您可以使用此代码使用HtmlAgilityPack检索所有exe

HtmlWeb web = new HtmlWeb();
HtmlDocument doc = web.Load("http://yourWebSite.com");

var itemList = doc.DocumentNode.SelectNodes("//a[@href]")//get all hrefs
                  .Select(p => p.Attributes["href"].Value)
                  .Where(x=>x.EndsWith("exe"))
                  .ToList();

itemList现在包含所有exe

,而不是使用正则表达式,您可以只使用普通代码

        List<string> files = new List<string>();
        string[] parts = htmlText.Split(new string[]{"\""},                
             StringSplitOptions.RemoveEmptyEntries);
        foreach (string part in parts)
        {
            if (part.EndsWith(".exe"))
                files.Add(part);
        }
在这种情况下,您将在文件列表中找到所有文件

编辑: 你可以做:

List<string> files = new List<string>();
string[] hrefs = htmlText.Split(new string[]{"href=\""},                
     StringSplitOptions.RemoveEmptyEntries);
foreach (string href in hrefs)
{
     string[] possibleFile = href.Split(new string[]{"\""}, 
           StringSplitOptions.RemoveEmptyEntries);
     if (possibleFile.Length() > 0 && possibleFile[0].EndsWith(".exe"))
         files.Add(possibleFile[0]);
}
这还将检查exe文件是否在a href中。

我将使用,它将类似jQuery的语法添加到HtmlAlityPack中。使用ends with selector测试href属性:

using HtmlAgilityPack;
using Fizzler.Systems.HtmlAgilityPack;

var web = new HtmlWeb();
var document = web.Load("http://example.com/page.html")
var page = document.DocumentNode;

foreach(var item in page.QuerySelectorAll("a[href$='exe']"))
{
    var file = item.Attributes["href"].Value;
}

解释为什么用正则表达式解析HTML是不好的:

这不是答案,但对于注释来说太长了。我稍后会删除它

为了解决问题,它起作用,它不起作用等等;一个完整的代码,供那些可能想要检查的人使用

string html = @"<a href=""download/datavoila-setup.exe"" id=""button_download"" title=""Download your copy of DataVoila!"" onclick=""pageTracker._trackPageview('/download/datavoila-setup.exe')""></a>";
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(html);


//Anirudh's Solution
var itemList = doc.DocumentNode.SelectNodes("//a//@href")//get all hrefs
                .Select(p => p.InnerText)
                .Where(x => x.EndsWith("exe"))
                .ToList();
//returns empty list 


//correct one      
var itemList2 = doc.DocumentNode.SelectNodes("//a[@href]") 
                 .Select(p => p.Attributes["href"].Value)
                 .Where(x => x.EndsWith("exe"))
                 .ToList();
 //returns download/datavoila-setup.exe

我会使用[href$='exe']语法来获取页面中的所有元素1 SelectNodes//a/@href selects as not hrefs 2。Selectp=>p.InnerText.endswixe选择一个布尔变量,这样您就有了一个布尔列表。@I4V更正..谢谢..但第一部分是正确的..它会选择hrefs..我没有使用//a[@href] xpath@Anirudh请参见名称SelectNodes。它选择节点而不是属性。不要相信你的头脑,检查它。@Anirudh我应该吗?我用问题中的html片段测试了您的代码。但它并没有像我预期的那样工作。我在itemlist上得到一个空值。知道为什么吗?:但我必须补充一点,这个解决方案不需要任何外部库。我只想在页面上提取带有.exe的文件-这表明存在未知数量的元素。这假设您已经检索到了元素。实际上,我也尝试了您的代码,它工作正常。唯一的问题是,与上述答案相比,这并不是一个清晰的答案。你能像上面那样用href简化htmlText.split吗?如果你能做到,也许我可以改变主意,选择这个作为答案。谢谢@Anirudh那么这意味着什么?我在LINQPAD中测试了它。它有效吗?我测试并转储了输出。我看到的是锚的内部文本的输出,而不是href。我匆忙地假设它是href的,但从来没有考虑到我正在寻找href'sNice catch的事实。尽管如此,我还是更喜欢fizzerex语法:-实际上我喜欢这种捕获方法,但我得到了一个错误:HtmlDocument doc=newhtmldocument上没有可用的源代码;你知道为什么吗我得到了itemList2的空值:
using HtmlAgilityPack;
using Fizzler.Systems.HtmlAgilityPack;

var web = new HtmlWeb();
var document = web.Load("http://example.com/page.html")
var page = document.DocumentNode;

foreach(var item in page.QuerySelectorAll("a[href$='exe']"))
{
    var file = item.Attributes["href"].Value;
}
string html = @"<a href=""download/datavoila-setup.exe"" id=""button_download"" title=""Download your copy of DataVoila!"" onclick=""pageTracker._trackPageview('/download/datavoila-setup.exe')""></a>";
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(html);


//Anirudh's Solution
var itemList = doc.DocumentNode.SelectNodes("//a//@href")//get all hrefs
                .Select(p => p.InnerText)
                .Where(x => x.EndsWith("exe"))
                .ToList();
//returns empty list 


//correct one      
var itemList2 = doc.DocumentNode.SelectNodes("//a[@href]") 
                 .Select(p => p.Attributes["href"].Value)
                 .Where(x => x.EndsWith("exe"))
                 .ToList();
 //returns download/datavoila-setup.exe