网络爬虫
网络爬虫(web crawler):自动抓取互联网信息的程序。
比如我们要开发一个网站,在网页的右上角需要显示今日天气,如果人工查询天气预报维护非常繁琐,我们就可以使用爬虫程序自动爬取天气网站的程序,自动更新。
Jsoup可以通过URL获取网页的HTML源文件,源文件中包含着网站数据,我们可以解析HTML源文件的数据来获取我们需要的信息。
爬虫步骤:
- 引入jar包。
- 使用Jsoup获取网页HTML源文件,转为Document对象
- 通过Document对象,获取需要的Element对象
- 获取Element对象的数据。
- 设置循环自动爬取 ```java import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.select.Elements;
import java.net.URL;
public class CrawlerDemo { public static void main(String[] args) { int min=9749756; int max=9749847; //循环爬取数据
for(int i = min;i<=max;i++) {
try {
//使用Jsoup获取网页HTML源文件,转为Document对象
Document document = Jsoup.parse(new URL("https://daily.zhihu.com/story/"+i), 3000);
// System.out.println(document); //通过Document对象,获取需要的Element对象 Elements headerImgEle = document.getElementsByAttributeValue(“alt”, “头图”); Elements titleEle = document.select(“.DailyHeader-title”); Elements authorEle = document.select(“.author”); Elements contentEle = document.select(“.content”); //获取Element对象的数据。 System.out.println(headerImgEle.get(0).attr(“src”)); System.out.println(titleEle.get(0).text()); System.out.println(authorEle.get(0).text()); System.out.println(contentEle.get(0).text()); }catch (Exception e){ e.printStackTrace(); } } } }
<a name="VjgpR"></a>
### 使用XML配置爬虫程序的参数
爬虫程序有一些参数需要配置,如果直接将参数写在JAVA程序中,则修改参数非常不方便,所以此时我们将参数写在XML配置文件中,通过解析XML文件获取参数的配置信息。<br />1、编写爬虫程序的XML配置文件Crawler.xml
```xml
<?xml version="1.0" ?>
<crawler>
<min>9749756</min>
<max>9749847</max>
</crawler>
package crawler;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import java.io.File;
import java.io.IOException;
import java.net.URL;
public class CrawlerDemo {
public static void main(String[] args) throws IOException {
//解析xml配置文件
String path=CrawlerDemo.class.getClassLoader().getResource("crawler/Crawler.xml").getPath();
Document document1 = Jsoup.parse(new File(path),"utf-8");
Elements minEle=document1.getElementsByTag("min");
Elements maxEle = document1.getElementsByTag("max");
int min =Integer.parseInt(minEle.get(0).text()) ;
int max = Integer.parseInt(maxEle.get(0).text());
//循环爬取数据
for(int i = min;i<=max;i++) {
try {
//使用Jsoup获取网页HTML源文件,转为Document对象
Document document = Jsoup.parse(new URL("https://daily.zhihu.com/story/"+i), 3000);
// System.out.println(document);
//通过Document对象,获取需要的Element对象
Elements headerImgEle = document.getElementsByAttributeValue("alt", "头图");
Elements titleEle = document.select(".DailyHeader-title");
Elements authorEle = document.select(".author");
Elements contentEle = document.select(".content");
//获取Element对象的数据。
System.out.println(headerImgEle.get(0).attr("src"));
System.out.println(titleEle.get(0).text());
System.out.println(authorEle.get(0).text());
System.out.println(contentEle.get(0).text());
}catch (Exception e){
e.printStackTrace();
}
}
}
}