Selenium之免登录获取CSDN代码块内容(Java)

Selenium安装配置可见:Selenium安装及配置和Python/Java案例-CSDN博客

 免登录获取CSDN代码块内容

package com.fuqying;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.time.Duration;
import java.util.List;

public class SeleniumDemo {

    public static void main(String[] args) {
        System.out.println("开始.");

        //这里修改一下路径
        System.setProperty("webdriver.chrome.driver", "/Users/fuqying/fuqy/dev/chromedriver/chromedriver");

        //实例化驱动
        WebDriver driver = new ChromeDriver();

        // 打开网页
        driver.get("https://blog.csdn.net/weixin_47470990/article/details/145014782");
        JavascriptExecutor js = (JavascriptExecutor) driver;
        try {
            //页面加载超时时间
            driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(10));
        } catch (Exception e) {
        } finally {
            System.out.println("页面加载完成...");
            //最大化窗口
            driver.manage().window().maximize();
            //使用 JavaScript 将页面缩放比例设置为 75%:"document.body.style.zoom = '75%';
            //滚动到底部:window.scrollTo(0, document.body.scrollHeight);
            js.executeScript("document.body.style.zoom = '75%';window.scrollTo(0, document.body.scrollHeight);");
            //js.executeScript("window.stop();");
        }

        WebElement closeImgEle = new WebDriverWait(driver, Duration.ofSeconds(5))
                .until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[@id='passportbox']//img")));
        closeImgEle.click();
        System.out.println("关闭登录窗口完成!");

        //定位所有代码块元素
        List codeTexts = driver.findElements(By.xpath("//pre[@name='code']"));

        for(WebElement codeText : codeTexts) {
            //滚动到元素的位置
            js.executeScript("arguments[0].scrollIntoView(true);", codeText);
            String seqNo = "data-index=" + codeText.getDomAttribute("data-index");
            System.out.println("=========================================" + seqNo + " 开始");

            try {
                //展开折叠的代码块
                WebElement hidCodeEle = codeText.findElement(By.xpath("//pre[@data-index='" + codeText.getDomAttribute("data-index") + "']//span[@class='hide-preCode-bt']"));
                js.executeScript("arguments[0].click();", hidCodeEle);
            } catch (Exception e) {
            }

            String text = codeText.getText();
            System.out.println(text);
            System.out.println("=========================================" + seqNo + " 结束");
        }

        System.out.println("完成!");

        // 关闭浏览器
        driver.quit();
    }
}

你可能感兴趣的:(selenium,java)