爬虫+模拟登录

16 篇文章 0 订阅
8 篇文章 0 订阅

在一些爬虫中,需要用到账号登录进入,才能看到需要爬取的内容,因此实现程序自动模拟登录非常有必要。

目前大部分网站的登录,都是使用表单提交的方法实现的,这一类网站的模拟登录,相信度娘已经给出来的许多实例。还有一类网站不是使用网页自带表单提交的方法,网站自己实现了js方法来登录,这就需要进行特别的模拟浏览器行为。

本文用到的主要技术手段包括Selenium+Phantomjs+Jsoup。

WebDriver

/**
* @DESC 获取PhantomJSDriver
* @param phantomJS
* @return WebDriver
*/
public static WebDriver getPhantomJs(String phantomJS) {

        System.setProperty("phantomjs.binary.path", phantomJS);

        DesiredCapabilities desiredCapabilities = DesiredCapabilities
                .phantomjs();
        desiredCapabilities.setJavascriptEnabled(true);
        String headers = getHeaders();// 生成随机User_Agent
        desiredCapabilities.setCapability("phantomjs.page.settings.userAgent",
                headers);
        desiredCapabilities.setCapability(
                "phantomjs.page.customHeaders.User-Agent", headers);

        PhantomJSDriver driver = new PhantomJSDriver(desiredCapabilities);
        driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);

        return driver;
    }

模拟登录

public static void main(String[] args) throws IOException {

        WebDriver wd = getPhantomJs("Your Phantomjs Path");
        wd.get("Target Website");
        wd.findElement(By.id("txtUserName")).sendKeys(
                "Your Account");
        wd.findElement(By.id("txtPassword")).sendKeys("Your Passwd");
        JavascriptExecutor js = (JavascriptExecutor) wd;
        js.executeScript("网站登录方法[一般会在JS中找到,或触发,或点击]");
        try {// 等待登录加载完成
            Thread.sleep(PAUSE_TIME);
        } catch (InterruptedException e) {
        }
        Set<Cookie> coks = wd.manage().getCookies();
        wd.quit();

        // 保存登录的Cookies
        Map<String, String> cookies = new HashMap<String, String>();
        for (Cookie ck : coks)
            cookies.put(ck.getName(), ck.getValue());

    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值