如何使用c#正则表达式获取Image的源代码? [英] How to get the source of Image using c# regular Expression?

查看:454
本文介绍了如何使用c#正则表达式获取Image的源代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下代码来获取给定html的图像。我在这里使用的asp控件是TextBox,Image,Button。提供网站链接后点击按钮的事件如下:



I used the following code to get Image of the given html.. The asp controls that I used here are TextBox, Image, Button. The event for the button click after providing the website link is as follows..

protected void GetImage_Click(object sender, EventArgs e)
{
string mySite = TextBox1.Text;
WebClient wc = new WebClient();
string getData = wc.DownloadString(mySite);
string result = Regex.Match(getData, "<img.+?src=[\"'](.+?)[\"'].+?>",RegexOptions.IgnoreCase).Groups[1].Value;
Image1.ImageUrl= result;
}





我不知道代码中的问题是什么。当我使用REGULAR EXPRESSION时,我总是遇到麻烦...请建议我一个工作正常的解决方案...



I dont know what''s the problem in my code. I am always getting into trouble while I use REGULAR EXPRESSION... Please do suggest me a solution that works fine...

推荐答案

我刚刚尝试了正则表达式本身一个示例html文件,它返回了文件中的第一个图像URL。



所以,你需要看看你下载数据的方式,以及它是什么实际下载 - 它可能不是你的想法!



BTW:最好将Match写入Match类实例,并检查Success属性之前试图访问结果。并使用命名组而不是匿名组,因此您不必在代码中使用幻数!
I just tried the regex itself with a sample html file, and it returned the first image URL in the file.

So, you need to look at the way you are downloading the data, and what it actually downloads - it may not be what you think!

BTW: It is a good idea to read the Match into a Match class instance, and check the Success property before trying to access the results. And use named groups rather than anonymous, so you don''t have to use magic numbers in your code!


这篇关于如何使用c#正则表达式获取Image的源代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆