Main Content

下载网页和文件

MATLAB® 提供了两个用于从 RESTful Web 服务读取内容的函数:webreadwebsave。利用 webread 函数,您可以将网页内容读取到 MATLAB 工作区内的字符数组中。利用 websave 函数,您可以将网页内容保存到文件。

由于 webread 函数可以在工作区内创建字符数组,因此它非常适合在 MATLAB 中处理网页内容。websave 函数适用于将网页保存到本地文件夹。

注意

webread 以字符数组形式返回 HTML 时,请记住,它仅检索了该特定网页中的 HTML。超链接目标、图像等均未检索。

如果您需要向网页传递参数,利用 webreadwebsave 函数可以将这些参数定义为 Name, Value 对组参量。有关详细信息,请参阅 webreadwebsave 参考页。

示例 - 使用 webread 函数

以下过程展示了如何检索网页内容,该网页中列出了提交到 MATLAB Central™ File Exchange https://www.mathworks.com/matlabcentral/fileexchange/ 的文件。它将结果赋给字符数组 fullList

filex = 'https://www.mathworks.com/matlabcentral/fileexchange/';
fullList = webread(filex);

仅检索过去 7 天内上传至 File Exchange 且包含单词 Simulink® 的文件的列表。将 durationterm 设为 webread 将传递至网页的参数。

filex = 'https://www.mathworks.com/matlabcentral/fileexchange/';
recent = webread(filex,'duration',7,'term','simulink');

示例 - 使用 websave 函数

以下示例基于前面部分的过程构建,但将内容保存至文件:

% Locate the list of files at the MATLAB Central File Exchange
% uploaded within the past 7 days, that contain "Simulink."
filex = 'https://www.mathworks.com/matlabcentral/fileexchange/';

% Save the Web content to a file.
recent = websave('contains_simulink.html',filex, ...
    'duration',7,'term','simulink');

MATLAB 将网页另存为 contains_simulink.html。输出参量 recent 包含 contains_simulink.html 的完整路径。调用 web 函数,以便在浏览器中显示 contains_simulink.html

web(recent)

此页面包含了已上传至 MATLAB Central File Exchange 的文件的链接。