专业网站建设品牌,十四年专业建站经验,服务6000+客户--广州京杭网络
免费热线:400-963-0016      微信咨询  |  联系我们

c#使用正则表达式抓取a标签的链接和innerhtml

当前位置:网站建设 > 技术支持
资料来源:网络整理       时间:2023/2/14 0:38:15       共计:3634 浏览
//读取网页html
            string text = File.ReadAllText(Environment.CurrentDirectory + "//test.txt", Encoding.GetEncoding("gb2312"));
            string prttern = "<a(\\s+(href=\"(?<url>([^\"])*)\"|'([^'])*'|\\w+=\"(([^\"])*)\"|'([^'])*'))+>(?<text>(.*?))</a>";
            var maths = Regex.Matches(text, prttern);
            //抓取出来写入的文件
            using (FileStream w = new FileStream(Environment.CurrentDirectory + "//wirter.txt", FileMode.Create))
            {

                for (int i = 0; i < maths.Count; i++)
                {
                    byte[] bs = Encoding.UTF8.GetBytes(string.Format("链接地址:{0},   innerhtml:{1}", maths[i].Groups["url"].Value,
                        maths[i].Groups["text"].Value) + "\r\n");
                    w.Write(bs, 0, bs.Length);
                    Console.WriteLine();
                }
            }

            Console.ReadKey();


图解正则

 

朋友需要截取img标签的src 和data-url   跟上面差不多。。顺便附上

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 string text =File.ReadAllText(Environment.CurrentDirectory + "//test.txt", Encoding.GetEncoding("gb2312"));            string prttern = "<img(\\s*(src=\"(?<src>[^\"]*?)\"|data-url=\"(?<dataurl>[^\"]*?)\"|[-\\w]+=\"[^\"]*?\"))*\\s*/>";            var maths = Regex.Matches(text, prttern);            //抓取出来写入的文件            using (FileStream w = new FileStream(Environment.CurrentDirectory + "//wirter.txt", FileMode.Create))            {                  for (int i = 0; i < maths.Count; i++)                {                    byte[] bs = Encoding.UTF8.GetBytes(string.Format("图片src:{0},   图片data-url:{1}", maths[i].Groups["src"].Value,                        maths[i].Groups["dataurl"].Value) + "\r\n");                    w.Write(bs, 0, bs.Length);                    Console.WriteLine();                }            }


 

版权说明:
本网站凡注明“广州京杭 原创”的皆为本站原创文章,如需转载请注明出处!
本网转载皆注明出处,遵循行业规范,如发现作品内容版权或其它问题的,请与我们联系处理!
欢迎扫描右侧微信二维码与我们联系。
·上一条:VS2017git 提交提示错误 Git failed with a fatal error. | ·下一条:C# HtmlAgilityPack+Selenium爬取需要拉动滚动条的页面内容

Copyright © 广州京杭网络科技有限公司 2005-2025 版权所有    粤ICP备16019765号 

广州京杭网络科技有限公司 版权所有