網頁數據抓取 獲取股票數據


/*
* import java.io.BufferedReader;
* import java.io.File;
* import java.io.FileReader;
* import java.io.IOException;
* import java.util.regex.Matcher;
* import java.util.regex.Pattern;
*/
import java.net.*;
import java.io.*;
import java.util.regex.*;
public class DataSpider {

public static void main(String[] args) throws IOException {


String s;
int i = 0;

//網頁地址
URL url = new URL(
"http://money.finance.sina.com.cn/corp/go.php/vMS_MarketHistory/stockid/600006.phtml");
//創建輸入流
BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
//創建輸出文檔
FileOutputStream fos = new FileOutputStream("D:\\XiAoOMAn\\GuPiao.txt");
//創建輸出流
OutputStreamWriter ows = new OutputStreamWriter(fos);

//匹配需要獲取的數據的列名
Pattern q = Pattern.compile("((?<=g>)(\\w*?)).*?(?=(</strong>))");
//匹配數據
Pattern p = Pattern.compile("((?<=date=)(\\w*?)).*?(?=('>))|((?<=center\">)(\\d{1,7}?)).*?(?=(</div>))");
String str = null;
//獲取源文件內容 匹配 輸出
while ((str = br.readLine()) != null) {
// Matcher b = q.matcher(str);
//列名
Matcher n = q.matcher(str);
//數據
Matcher m = p.matcher(str);

//提取 列名
while (n.find()) {
//形式轉換 成 String
s = String.valueOf(n.group());
//輸出到文本文檔
ows.write(s + " ");
System.out.printf("%-44s", n.group());

}
//提取 數據
while (m.find()) {
if (i == 0){
System.out.println();
ows.write("\r\n");
}
i++;
s = String.valueOf(m.group());
ows.write(s + " ");
System.out.printf("%-22s", m.group());
//每輸出完一行 回車
if (i % 7 == 0)
{
System.out.println();
ows.write("\r\n");
}
}

}
ows.close();
fos.close();
br.close();
br.close();

}

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章