---
title: "抓取网站信息"
author: "maybe723"
date: "2008-07-19T11:31:20Z"
tags: []
slug: "untitled"
draft: false
lastmod: "2008-07-19T11:31:20Z"
id: 216466
url: "https://maybe723.iteye.com/blog/216466"
---

接触正则表达式的时间不长,感觉挺有意思,所以试着抓取了一下某网站数据.

Code:

```
private String getInformation(String t)
    {

        Regex r;
        Match m;
        r=new Regex("<tr\\s*bgcolor=\"#FFFFFF\">(?<1>(.|\n)*?)</tr>",RegexOptions.Compiled|RegexOptions.IgnoreCase);

        StringBuilder sql = new StringBuilder();
        for (m = r.Match(t); m.Success; m = m.NextMatch())
        {
            string buffer = m.Groups[1].Value.Trim();
            Regex rx;
            rx = new Regex("<td height=\"28\"\\s.*align=\"center\"><a href=\"(?<1>.*)\"\\s.*target=\"_blank\">(?<2>.*)</a></td>\\s*<td height=\"28\"\\s.*align=\"center\">(?<3>.*)</td>\\s*[\\s|\\S]*<td width=\"236\"\\s*align=\"center\">(?<4>.*)</td>", RegexOptions.Compiled | RegexOptions.IgnoreCase);
          

            String companyUrl = rx.Match(buffer).Groups[1].Value.Trim();
            String companyName = rx.Match(buffer).Groups[2].Value.Trim();
            if (companyName.Contains("font"))
            {
                Regex rn;
                rn = new Regex("<font\\s*color=\"#FF0000\">(?<1>.*)</font>", RegexOptions.Compiled | RegexOptions.IgnoreCase);
                companyName = rn.Match(companyName).Groups[1].Value.Trim();
            }
            String companyRegion = rx.Match(buffer).Groups[3].Value.Trim();
            String companyBrand = rx.Match(buffer).Groups[4].Value.Trim();
          
            sql.AppendLine("insert into information values('"+companyName+"','"+companyUrl+"','"+companyRegion+"','"+companyBrand+"');");
        }
      
        return sql.ToString();

 
    }
```