详解Java豆瓣电影爬虫——小爬虫成长记(附源码)
以前也用过爬虫,比如使用nutch爬取指定种子,基于爬到的数据做搜索,还大致看过一些源码。当然,nutch对于爬虫考虑的是十分全面和细致的。每当看到屏幕上唰唰过去的爬取到的网页信息以及处理信息的时候,总感觉这很黑科技。正好这次借助梳理spring mvc的机会,想自己弄个小爬虫,简单没关系,有些小bug也无所谓,我需要的只是一个能针对某个种子网站能爬取我想要的信息就可以了。有exception就去解决,可能是一些api使用不当,也可能是遇到了http请求状态异常,又或是数据库读写有问题,就是在这个报exception和解决exception的过程中,jewelcrawler(儿子的小名)已经可以能够独立的爬取数据,并且还有一项基于word2vec算法做个情感分析的小技能。
后面可能还会有未知的exception等着解决,也有一些性能需要优化,比如和数据库的交互,数据的读写等等。但是目测年内没有太多精力放这上面了,所以今天做一个简单的总结,而且前两篇主要侧重的是功能和结果,这篇来说说jewelcrawler是如何诞生的,并将代码放到github上(源码地址在文章最后),有兴趣的可以关注下(仅供交流学习,请勿他用,考虑下douban君。多一点真诚,少一点伤害)
环境介绍
开发工具:intellij idea 14
数据库: mysql 5.5 + 数据库管理工具navicat(可用来连接查询数据库)
语言:java
jar包管理:maven
版本管理:git
目录结构
其中
com.ansj.vec是word2vec算法的java版本实现
com.jackie.crawler.doubanmovie是爬虫实现模块,其中又包括
有些包是空的,因为这些模块还没有用上,其中
- constants包是存放常量类
- crawl包存放爬虫入口程序
- entity包映射数据库表的实体类
- test包存放测试类
- utils包存放工具类
resource模块存放的是配置文件和资源文件,比如
- beans.xml:spring上下文的配置文件
- seed.properties:种子文件
- stopwords.dic:停用词库
- comment12031715.txt:爬取的短评数据
- tokenizerresult.txt:使用ikanalyzer分词后的结果文件
- vector.mod:基于word2vec算法训练的模型数据
test模块是测试模块,用于编写ut.
数据库配置
1. 添加依赖的包
jewelcrawler使用的maven管理,所以只需要在pom.xml中添加相应的依赖就可以了
<dependency> <groupid>org.springframework</groupid> <artifactid>spring-jdbc</artifactid> <version>4.1.1.release</version> </dependency> <dependency> <groupid>commons-pool</groupid> <artifactid>commons-pool</artifactid> <version>1.6</version> </dependency> <dependency> <groupid>commons-dbcp</groupid> <artifactid>commons-dbcp</artifactid> <version>1.4</version> </dependency> <dependency> <groupid>mysql</groupid> <artifactid>mysql-connector-java</artifactid> <version>5.1.38</version> </dependency> <dependency> <groupid>mysql</groupid> <artifactid>mysql-connector-java</artifactid> <version>5.1.38</version> </dependency>
2. 声明数据源bean
我们需要在beans.xml中声明数据源的bean
<context:property-placeholder location="classpath*:*.properties"/> <bean id="datasource" class="org.apache.commons.dbcp.basicdatasource" destroy-method="close"> <property name="driverclassname" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean>
注意: 这里是绑定了外部配置文件jdbc.properties,具体数据源的参数从该文件读取。
如果遇到问题“sql [insert into user(id) values(?)]; field 'name' doesn't have a default value;”解决方法是设置表的相应字段为自增长字段。
解析页面遇到的问题
对于爬到的网页数据需要解析dom结构,拿到自己想要的数据,期间遇到如下错误
org.htmlparser.node不识别
解决方法:添加jar包依赖
<dependency> <groupid>org.htmlparser</groupid> <artifactid>htmlparser</artifactid> <version>1.6</version> </dependency>
org.apache.http.httpentity不识别
解决方法:添加jar包依赖
<dependency> <groupid>org.apache.httpcomponents</groupid> <artifactid>httpclient</artifactid> <version>4.5.2</version> </dependency>
当然这是期间遇到的问题,最后用的是jsoup做的页面解析。
maven仓库下载速度慢
之前使用的是默认的maven*仓库,下载jar包的速度很慢,不知道是我的网络问题还是其他原因,后来在网上找到了阿里云的maven仓库,更新后,相比之前简直是秒下,吐血推荐。
<mirrors> <mirror> <id>alimaven</id> <name>aliyun maven</name> <url>http://maven.aliyun.com/nexus/content/groups/public/</url> <mirrorof>central</mirrorof> </mirror> </mirrors>
找到maven的settings.xml文件,添加这个镜像即可。
读取resource模块下文件的一种方法
比如读取seed.properties文件
@test public void testfile(){ file seedfile = new file(this.getclass().getresource("/seed.properties").getpath()); system.out.print("===========" + seedfile.length() + "===========" ); }
有关正则表达式
使用regrex正则表达式的时候,如果匹配上了定义的pattern,则需要先调用matcher的find方法然后才能使用group方法找到子串。直接调用group方法是没有办法找到你想要的结果的。
我看了下上面matcher类的源码
package java.util.regex; import java.util.objects; public final class matcher implements matchresult { /** * the pattern object that created this matcher. */ pattern parentpattern; /** * the storage used by groups. they may contain invalid values if * a group was skipped during the matching. */ int[] groups; /** * the range within the sequence that is to be matched. anchors * will match at these "hard" boundaries. changing the region * changes these values. */ int from, to; /** * lookbehind uses this value to ensure that the subexpression * match ends at the point where the lookbehind was encountered. */ int lookbehindto; /** * the original string being matched. */ charsequence text; /** * matcher state used by the last node. noanchor is used when a * match does not have to consume all of the input. endanchor is * the mode used for matching all the input. */ static final int endanchor = 1; static final int noanchor = 0; int acceptmode = noanchor; /** * the range of string that last matched the pattern. if the last * match failed then first is -1; last initially holds 0 then it * holds the index of the end of the last match (which is where the * next search starts). */ int first = -1, last = 0; /** * the end index of what matched in the last match operation. */ int oldlast = -1; /** * the index of the last position appended in a substitution. */ int lastappendposition = 0; /** * storage used by nodes to tell what repetition they are on in * a pattern, and where groups begin. the nodes themselves are stateless, * so they rely on this field to hold state during a match. */ int[] locals; /** * boolean indicating whether or not more input could change * the results of the last match. * * if hitend is true, and a match was found, then more input * might cause a different match to be found. * if hitend is true and a match was not found, then more * input could cause a match to be found. * if hitend is false and a match was found, then more input * will not change the match. * if hitend is false and a match was not found, then more * input will not cause a match to be found. */ boolean hitend; /** * boolean indicating whether or not more input could change * a positive match into a negative one. * * if requireend is true, and a match was found, then more * input could cause the match to be lost. * if requireend is false and a match was found, then more * input might change the match but the match won't be lost. * if a match was not found, then requireend has no meaning. */ boolean requireend; /** * if transparentbounds is true then the boundaries of this * matcher's region are transparent to lookahead, lookbehind, * and boundary matching constructs that try to see beyond them. */ boolean transparentbounds = false; /** * if anchoringbounds is true then the boundaries of this * matcher's region match anchors such as ^ and $. */ boolean anchoringbounds = true; /** * no default constructor. */ matcher() { } /** * all matchers have the state used by pattern during a match. */ matcher(pattern parent, charsequence text) { this.parentpattern = parent; this.text = text; // allocate state storage int parentgroupcount = math.max(parent.capturinggroupcount, 10); groups = new int[parentgroupcount * 2]; locals = new int[parent.localcount]; // put fields into initial states reset(); } .... /** * returns the input subsequence matched by the previous match. * * <p> for a matcher <i>m</i> with input sequence <i>s</i>, * the expressions <i>m.</i><tt>group()</tt> and * <i>s.</i><tt>substring(</tt><i>m.</i><tt>start(),</tt> <i>m.</i><tt>end())</tt> * are equivalent. </p> * * <p> note that some patterns, for example <tt>a*</tt>, match the empty * string. this method will return the empty string when the pattern * successfully matches the empty string in the input. </p> * * @return the (possibly empty) subsequence matched by the previous match, * in string form * * @throws illegalstateexception * if no match has yet been attempted, * or if the previous match operation failed */ public string group() { return group(0); } /** * returns the input subsequence captured by the given group during the * previous match operation. * * <p> for a matcher <i>m</i>, input sequence <i>s</i>, and group index * <i>g</i>, the expressions <i>m.</i><tt>group(</tt><i>g</i><tt>)</tt> and * <i>s.</i><tt>substring(</tt><i>m.</i><tt>start(</tt><i>g</i><tt>),</tt> <i>m.</i><tt>end(</tt><i>g</i><tt>))</tt> * are equivalent. </p> * * <p> <a href="pattern.html#cg">capturing groups</a> are indexed from left * to right, starting at one. group zero denotes the entire pattern, so * the expression <tt>m.group(0)</tt> is equivalent to <tt>m.group()</tt>. * </p> * * <p> if the match was successful but the group specified failed to match * any part of the input sequence, then <tt>null</tt> is returned. note * that some groups, for example <tt>(a*)</tt>, match the empty string. * this method will return the empty string when such a group successfully * matches the empty string in the input. </p> * * @param group * the index of a capturing group in this matcher's pattern * * @return the (possibly empty) subsequence captured by the group * during the previous match, or <tt>null</tt> if the group * failed to match part of the input * * @throws illegalstateexception * if no match has yet been attempted, * or if the previous match operation failed * * @throws indexoutofboundsexception * if there is no capturing group in the pattern * with the given index */ public string group(int group) { if (first < 0) throw new illegalstateexception("no match found"); if (group < 0 || group > groupcount()) throw new indexoutofboundsexception("no group " + group); if ((groups[group*2] == -1) || (groups[group*2+1] == -1)) return null; return getsubsequence(groups[group * 2], groups[group * 2 + 1]).tostring(); } /** * attempts to find the next subsequence of the input sequence that matches * the pattern. * * <p> this method starts at the beginning of this matcher's region, or, if * a previous invocation of the method was successful and the matcher has * not since been reset, at the first character not matched by the previous * match. * * <p> if the match succeeds then more information can be obtained via the * <tt>start</tt>, <tt>end</tt>, and <tt>group</tt> methods. </p> * * @return <tt>true</tt> if, and only if, a subsequence of the input * sequence matches this matcher's pattern */ public boolean find() { int nextsearchindex = last; if (nextsearchindex == first) nextsearchindex++; // if next search starts before region, start it at region if (nextsearchindex < from) nextsearchindex = from; // if next search starts beyond region then it fails if (nextsearchindex > to) { for (int i = 0; i < groups.length; i++) groups[i] = -1; return false; } return search(nextsearchindex); } /** * initiates a search to find a pattern within the given bounds. * the groups are filled with default values and the match of the root * of the state machine is called. the state machine will hold the state * of the match as it proceeds in this matcher. * * matcher.from is not set here, because it is the "hard" boundary * of the start of the search which anchors will set to. the from param * is the "soft" boundary of the start of the search, meaning that the * regex tries to match at that index but ^ won't match there. subsequent * calls to the search methods start at a new "soft" boundary which is * the end of the previous match. */ boolean search(int from) { this.hitend = false; this.requireend = false; from = from < 0 ? 0 : from; this.first = from; this.oldlast = oldlast < 0 ? from : oldlast; for (int i = 0; i < groups.length; i++) groups[i] = -1; acceptmode = noanchor; boolean result = parentpattern.root.match(this, from, text); if (!result) this.first = -1; this.oldlast = this.last; return result; } ... }
原因是这样的:这里如果不先调用find方法,直接调用group,可以发现group方法调用group(int group),该方法的方法体中有if first<0,显然这里这个条件是成立的,因为first的初始值就是-1,所以这里会抛异常。但是如果调用find方法,可以发现,最终会调用search(nextsearchindex),注意这里的nextsearchindex已被last赋值,而last的值为0,再跳转到search方法中
boolean search(int from) { this.hitend = false; this.requireend = false; from = from < 0 ? 0 : from; this.first = from; this.oldlast = oldlast < 0 ? from : oldlast; for (int i = 0; i < groups.length; i++) groups[i] = -1; acceptmode = noanchor; boolean result = parentpattern.root.match(this, from, text); if (!result) this.first = -1; this.oldlast = this.last; return result; }
这个nextsearchindex传给了from,而from在方法体中被赋值给了first,所以,调用了find方法之后,这个的first就不在是-1,也就不是抛异常了。
源码已经上传至百度网盘:http://pan.baidu.com/s/1dfwtvnz
以上说的问题比较碎,都是在遇到问题和解决问题的时候的一些总结。在具体操作的时候还会遇到其他问题,有问题或者建议的话欢迎提出来^^。
最后放几张截止目前爬取的数据
record表
其中存储的是79032条,爬取过的网页有48471条
movie表
目前爬取了2964部影视作品
comments表
爬取了29711条记录
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
下一篇: 浅谈在JAVA项目中LOG4J的使用