Matlab简单爬虫-寻宝天行诛仙在售角色信息

主要内容

偶然在网上看到matlab也可以写爬虫,而且流程很简单,记录一下学习过程和其中遇到的问题。主要包括简单爬虫的流程(2种方法),所用函数,weboptions设置(Timeout默认5s太短),正则表达式匹配简单提升效率的一个小的注意事项.

爬虫流程方法1

用actxserver(‘internetexplorer.application’)建立与ie浏览器的交互,到爬取网页源代码里找到所需信息的classname(F12加审查元素选取找到classname),之后提取class中的值获的想要爬取的信息。
F12+点选审查元素提取源代码中对应信息
这个方法是我最先看到的一种方法,但是不知道为什么actxserver这里我就会直接报错,所以没有成功…,想要具体学习这种方法建议直接去搜索更详细的教程。

ie=actxserver('internetexplorer.application');
ie.Navigate('网址');%输入爬取网址
ie.visible = 1;
source_info = ie.document.body.getElementsByClassName('classname') %classname 在浏览器中按F12,左上角选择元素点上,然后点选所需信息位置

爬虫流程方法2

使用webread函数直接读取该网页所有源代码,你所需要的信息就包含在里面,只不过因为是代码所以看起来杂乱无章,之后通过正则表达式匹配定位所需信息,提取这些信息,按顺序写入汇总表格。
简单以下图举个例子,我想获取价格信息,那么在源代码里面可以看到在“¥”符号之后跟着的数字就是价格。
正则表达式就可以写成 exp_price=’(?<=\¥)\d*.\d’。
它的意思就是从¥往后查找(数字(多位).数字(一位))这种规则的字符串,然后提取出来就是“6800.0”.
在这里插入图片描述
完整代码在这里,要注意网络响应时间这个参数设置方法。设置完之后再webread函数中记得也要写入实参options才有效。。

clear all;

%设置网络参数
options = weboptions;
options.Timeout=20; %默认是5s,容易出现连接响应超时而error.

%读取多页信息并汇总
txt_web=[];
for i=1:13 
    txt_web=[txt_web,webread(['网址page=',num2str(i)],options)]; %i对应页数,具体网址就不写了;不要忘记写options
end

%正则表达式
exp_character='(?<=职业\s).{2,3}';
exp_gender='(?<=性别\s).';
exp_level='(?<=\\r等级\s)\d{1,3}';
exp_camp='(?<=阵营\s).';
exp_primallevel='(?<=元神等级\s)\d{1,2}';
exp_attack='(?<=攻击\s)\d{1,6}\-\d{1,6}';
exp_defence='(?<=防御\s)\d{1,6}';
exp_blood='(?<=气血\s)\d{1,7}';
exp_magic='(?<=真气\s)\d{1,7}';
exp_name='(?<=\<dd\sstyle\=\"width\:145px\;\"\stitle\=\").{0,3}\*{0,3}';   
exp_price='(?<=\¥)\d*\.\d';
exp_location='(?<=\<dd\sstyle\=\"width\:80px\;height\:65px\;\soverflow\:hidden\;\"\stitle\=\").{2,6}(?=\")'; 
exp_commid='(?<=class\=\"buy\_button\"\svalue\=\"购买\"\sonclick\=\"location\.href\=.)http\:\/\/www\.xunbao178\.com\:80\/zx\/getServerList\?commid\=\d{5,10}';  

%匹配对应信息
character=regexp(txt_web,exp_character,'match');
character=reshape(character,[],1);
gender=regexp(txt_web,exp_gender,'match');
gender=reshape(gender,[],1);
level=regexp(txt_web,exp_level,'match');
level=reshape(level,[],1);
camp=regexp(txt_web,exp_camp,'match');
camp=reshape(camp,[],1);
primal_level=regexp(txt_web,exp_primallevel,'match');
primal_level=reshape(primal_level,[],1);
attack=regexp(txt_web,exp_attack,'match');
attack=reshape(attack,[],1);
defence=regexp(txt_web,exp_defence,'match');
defence=reshape(defence,[],1);
blood=regexp(txt_web,exp_blood,'match');
blood=reshape(blood,[],1);
magic=regexp(txt_web,exp_magic,'match');
magic=reshape(magic,[],1);
name=regexp(txt_web,exp_name,'match');
name=reshape
  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值