为了账号安全,请及时绑定邮箱和手机立即绑定

用Java爬慕课网猿问(2)

标签:
爬虫

上一篇讲了怎么爬取猿问首页,本次讲讲怎么将猿问后续爬去完成

遗留的问题

运行后,可以看到程序结束了,但是浏览器并没有关闭。WebDriver有quit()方法,可以关闭浏览器。

相信你也注意到了,浏览器打开的速度很慢,最好的办法是浏览器重用。

改造

将BrowserUtils改造如下:

public class BrowserUtils {


  private static WebDriver webDriver = null;

  /**
   * 打开谷歌浏览器.
   *
   * @return 返回浏览器
   */
  private static void getInstanceByChrome() {
    try {
      String driverDirectory = "chromedriver.exe";
      ChromeDriverService src = new ChromeDriverService.Builder()
              .usingDriverExecutable(new File(driverDirectory)).usingAnyFreePort().build();
      src.start();
      ChromeOptions options = new ChromeOptions();
      ChromeDriver driver = new ChromeDriver(src, options);
      driver.manage().window().maximize();
      webDriver = driver;
    } catch (IOException e) {
      e.printStackTrace();
    }

  }

  public static WebDriver getWebDriver() {
    if (null == webDriver) {
      getInstanceByChrome();
    }
    return webDriver;
  }

  public static void quit() {
    if (null != webDriver) {
      webDriver.quit();
      webDriver = null;
    }
  }
}

一个程序只有一个浏览器实例,而且提供了基本的浏览器获取关闭的方法。

后续爬取分析

打开慕课网猿问,url为:https://www.imooc.com/wenda/

打开第二页猿问,url为:https://www.imooc.com/wenda/recommend/2

打开第三页猿问,url为:https://www.imooc.com/wenda/recommend/3

规律就是猿问的页码可通过变更url解决

所以接上节

将main的url变成https://www.imooc.com/wenda/recommend/2,即可爬去第二页

带来的问题

不同页面内的问题可能是一个,怎么办

最简单的改造,返回一个Map型的参数,以Url为key,Task为value

改进

简单改造如下:

  public Map<String, Task> getTask() {
    WebDriver webDriver = BrowserUtils.getWebDriver();
    if (null == webDriver) {
      throw new RuntimeException("浏览器获取失败");
    }
    webDriver.get(super.getUrl());
    List<WebElement> listElement = webDriver.findElements(By.cssSelector(".item.clearfix"));
    Map<String, Task> tasks = new HashMap<>(listElement.size() * 2);
    for (WebElement webElement : listElement) {
      WebElement titleElement = webElement.findElement(By.className("que-title"));
      String title = titleElement.getText();
      String url = titleElement.getAttribute("href");
      Task task = new Task();
      task.setTitle(title);
      task.setUrl(url);
      tasks.put(url, task);
    }
    return tasks;
  }

main方法改造如下:

  public static void main(String args[]) throws Exception {
    Map<String, Task> data = new MainHandler("https://www.imooc.com/wenda").getTask();
    for (int i = 2; i < 11; i++) {
      data.putAll(new MainHandler("https://www.imooc.com/wenda/recommend/" + i).getTask());
    }
    BrowserUtils.quit();
    data.forEach((k, v) -> {
      System.out.println("title:" + v.getTitle() + "  url:" + v.getUrl());
    });
  }

爬取10页的数据

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
JAVA开发工程师
手记
粉丝
2674
获赞与收藏
169

关注作者,订阅最新文章

阅读免费教程

  • 推荐
  • 23
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消