如何利用Matlab抓取网页数据
2019-01-01
%朋友需要做金融方面的分析,要求从网站上下载大量的数据,一个一个复制粘贴太费事。我写了一个简单的网络爬虫,主要用到正则表达式,可以自动下载网页源文件里面的数据。
clc;
clear;
warning off;
for year =2010:2011 %年份
for season =1:4 %季度
fprintf("%d年%d季度的数据...", year, season)
[sourcefile, status] =urlread(sprintf("http://vip.stock.finance.sina.com.cn/corp/go.php/vMS_MarketHistory/stockid/000001/type/S.phtml?year=%d&season=%d",year));
if ~status
error("读取出错!\n")
end
expr1 ="\s+(\d\d\d\d-\d\d-\d\d)\s*"; %获取日期("s"空格字符间的日期数据)
[datefile, date_tokens]= regexp(sourcefile, expr1, "match","tokens"); %返回正则表达式的两个关键字"match"和 "tokens"
date = cell(size(date_tokens));
for idx = 1:length(date_tokens)
date{idx} =date_tokens{idx}{1}; %length(date_tokens)行 1列
end
expr2 = "(\d*\.?\d*)