爬虫–selenium

爬虫–selenium

一、selenium简介

selenium原本是用于网页自动化测试,由于其直接操作的浏览器的特点,因此可用于网页抓取,且不易被查封。

二、准备

  1. 下载Block-image_v1.0.crx ,用于禁止图片加载,这样可以加快访问速度(网上搜下即可下载);
  2. 下载chromedriver.exe , 即chome驱动器;
  3. 下载chrome浏览器;

三、开发步骤

  1. 安装chrome浏览器;
  2. 运行chromedriver.exe驱动器;
  3. 添加maven依赖
<dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-server</artifactId>
    <version>3.0.1</version>
</dependency>
  1. 代码实例
public class ChromeCrawlerMain {
    public static void main(String[] args) throws Exception {
        chromeCrawler();
    }

    static void chromeCrawler() throws Exception {
        String url = "http://www.ifeng.com/";

        ChromeOptions ops = new ChromeOptions();
        ops.addExtensions(new File("C:\\book\\Block-image_v1.0.crx"));  //禁止加载图片插件

        DesiredCapabilities dc = DesiredCapabilities.chrome();
        dc.setCapability(ChromeOptions.CAPABILITY,ops);
        dc.setBrowserName("Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.32 Safari/537.36");

        WebDriver driver = new RemoteWebDriver(new URL("http://localhost:9515"),dc);  //driver的默认端口
        driver.manage().timeouts().setScriptTimeout(10, TimeUnit.SECONDS);
        driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
        driver.manage().timeouts().pageLoadTimeout(10,TimeUnit.SECONDS);

        driver.get(url);
//        String html = driver.getPageSource();
        WebElement headlineEle = driver.findElement(By.cssSelector("#headLineDefault > ul > ul:nth-child(1) > li.topNews > h1 > a"));
        String headline = headlineEle.getText();
        System.out.println(headline);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值