java爬虫抓取网页数据(一下java下抓取网页上特定内容的方法-之前java中访问http )
优采云 发布时间: 2021-11-29 06:02java爬虫抓取网页数据(一下java下抓取网页上特定内容的方法-之前java中访问http
)
在进入正题之前,我们先来了解一下java下抓取网页上特定内容的方法,也就是所谓的网络爬虫。本文仅涉及简单的文字信息和链接爬取。java中访问http的方式不超过两种。一种是使用原来的httpconnection,另一种是使用封装好的插件或者框架,比如httpclient、okHttp等。在测试和抓取网页信息的过程中,我使用的是jsoup工具,因为该工具没有只封装了http访问,还具有强大的html解析功能。可以参考详细的使用教程。
第一步是访问登陆页面
文档 doc = Jsoup.connect("").get();
第二步,使用jsoup的选择器选择网页所需内容的具体元素(使用正则表达式效率更高)。在这个例子中,目标网页是一个论坛,我们需要做的是抓取论坛首页所有帖子的标题名称和链接地址。
首先打开目标网址,使用谷歌浏览器浏览网页结构,找到结构对应的内容,如下图
然后选择区域
Elements links = doc.getElementsByAttributeValue("id","lphymodelsub");
接下来,获取选中区域的内容并保存到数组中
对于(元素链接:链接){
CatchModel c = new CatchModel();
String linkHref = ""+link.parent().attr("href");
String linkText = link.text();
c.setText(linkText);
c.setUrl(linkHref);
fistCatchList.add(c);
}
这样一个简单的爬行就完成了。
下一步是新浪微博的爬取。一般http访问新浪微博网站得到的html很简单,因为新浪微博首页是用js动态生成的,需要多次访问。请求和验证只能访问成功,所以为了方便抓取数据,我们通过了一个后门,就是访问新浪微博的移动端进行抓取。然而,随之而来的一个问题是,访问新浪微博并不重要。任一端都需要强制登录认证,所以我们需要在http请求中附加一个cookie进行用户认证。网上找了很久,想用webcontroller这个开源的爬虫框架。它易于访问且高效。我们来看看如何使用这个框架。
首先需要导入依赖包,WebController的ja包和selenium的jar包
下载链接:
使用Selenium获取cookie登录新浪微博(WeiboCN.java)
使用WebCollector和获取的cookies抓取新浪微博并提取数据(WeiboCrawler.java)
微博CN.java
import java.util.Set;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
/**
* 利用Selenium获取登陆新浪微博weibo.cn的cookie
* @author hu
*/
public class WeiboCN {
/**
* 获取新浪微博的cookie,这个方法针对weibo.cn有效,对weibo.com无效
* weibo.cn以明文形式传输数据,请使用小号
* @param username 新浪微博用户名
* @param password 新浪微博密码
* @return
* @throws Exception
*/
public static String getSinaCookie(String username, String password) throws Exception{
StringBuilder sb = new StringBuilder();
HtmlUnitDriver driver = new HtmlUnitDriver();
driver.setJavascriptEnabled(true);
driver.get("http://login.weibo.cn/login/");
WebElement mobile = driver.findElementByCssSelector("input[name=mobile]");
mobile.sendKeys(username);
WebElement pass = driver.findElementByCssSelector("input[name^=password]");
pass.sendKeys(password);
WebElement rem = driver.findElementByCssSelector("input[name=remember]");
rem.click();
WebElement submit = driver.findElementByCssSelector("input[name=submit]");
submit.click();
Set cookieSet = driver.manage().getCookies();
driver.close();
for (Cookie cookie : cookieSet) {
sb.append(cookie.getName()+"="+cookie.getValue()+";");
}
String result=sb.toString();
if(result.contains("gsid_CTandWM")){
return result;
}else{
throw new Exception("weibo login failed");
}
}
}
<p style="font-size:15px; line-height:1.5em; font-family:'Helvetica Neue',Helvetica,Arial,sans-serif; widows:auto">WeiboCrawler.javaimport cn.edu.hfut.dmic.webcollector.model.CrawlDatum;
import cn.edu.hfut.dmic.webcollector.model.CrawlDatums;
import cn.edu.hfut.dmic.webcollector.model.Page;
import cn.edu.hfut.dmic.webcollector.net.HttpRequest;
import cn.edu.hfut.dmic.webcollector.net.HttpResponse;
import cn.edu.hfut.dmic.webcollector.plugin.berkeley.BreadthCrawler;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
/**
* 利用WebCollector和获取的cookie爬取新浪微博并抽取数据
* @author hu
*/
public class WeiboCrawler extends BreadthCrawler {
String cookie;
public WeiboCrawler(String crawlPath, boolean autoParse) throws Exception {
super(crawlPath, autoParse);
/*获取新浪微博的cookie,账号密码以明文形式传输,请使用小号*/
cookie = WeiboCN.getSinaCookie("你的用户名", "你的密码");
}
@Override
public HttpResponse getResponse(CrawlDatum crawlDatum) throws Exception {
HttpRequest request = new HttpRequest(crawlDatum);
request.setCookie(cookie);
return request.getResponse();
}
@Override
public void visit(Page page, CrawlDatums next) {
int pageNum = Integer.valueOf(page.getMetaData("pageNum"));
/*抽取微博*/
Elements weibos = page.select("div.c");
for (Element weibo : weibos) {
System.out.println("第" + pageNum + "页\t" + weibo.text());
}
}
public static void main(String[] args) throws Exception {
WeiboCrawler crawler = new WeiboCrawler("weibo_crawler", false);
crawler.setThreads(3);
/*对某人微博前5页进行爬取*/
for (int i = 1; i