如何在Selenium自动化Chrome浏览器中模拟用户行为和交互?

亿牛云代理

Selenium是一个用于自动化Web应用程序测试的工具,它可以模拟真实的用户在浏览器中进行各种操作,如点击、输入、滚动等。Selenium支持多种浏览器,如Chrome、Firefox、Edge等,但是每种浏览器都需要相应的驱动程序才能与Selenium进行通信。本文将介绍如何在Selenium中使用Chrome浏览器,并且设置代理服务器来避免被目标网站识别。

要使用Selenium自动化Chrome浏览器,首先需要下载Chrome的驱动程序,即chromedriver,可以从这里下载:https://chromedriver.chromium.org/downloads。下载后,将chromedriver.exe文件放在一个合适的位置,并记住其路径。

然后,需要导入Selenium的Java库,可以使用Maven或Gradle来管理依赖。这里以Maven为例,只需在pom.xml文件中添加以下代码:

```xml

<dependencies>

    <dependency>

        <groupId>org.seleniumhq.selenium</groupId>

        <artifactId>selenium-java</artifactId>

        <version>4.1.0</version>

    </dependency>

</dependencies>

```

接下来,需要创建一个WebDriver对象,用于控制Chrome浏览器。为了设置代理服务器,需要创建一个ChromeOptions对象,并使用setProxy方法来指定代理信息。代理信息可以使用Proxy类来构造,需要设置代理类型、主机名、端口号、用户名和密码。以下是一个示例代码,实现抖音关键词搜索,并将搜索获取的结果进行分析,存入Excel文件:

```java

import org.apache.poi.ss.usermodel.*;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import org.openqa.selenium.By;

import org.openqa.selenium.Proxy;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.chrome.ChromeOptions;

import java.io.FileOutputStream;

import java.io.IOException;

import java.util.ArrayList;

import java.util.List;

public class SeleniumDemo {

    // 爬虫代理

    // 亿牛云 代理服务器

    final static String proxyUser = "16YUN";

    final static String proxyPass = "16IP";

    // 代理服务器

    final static String proxyHost = "www.16yun.cn";

    final static int proxyPort = 31111;

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

        // 设置chromedriver的路径

        System.setProperty("webdriver.chrome.driver", "D:\\chromedriver.exe");

        // 创建一个Proxy对象,用于设置代理信息

        Proxy proxy = new Proxy();

        // 设置代理类型为MANUAL,表示手动设置代理

        proxy.setProxyType(Proxy.ProxyType.MANUAL);

        // 设置http和https协议的代理主机名和端口号

        proxy.setHttpProxy(proxyHost + ":" + proxyPort);

        proxy.setSslProxy(proxyHost + ":" + proxyPort);

        // 设置代理的用户名和密码

        proxy.setSocksUsername(proxyUser);

        proxy.setSocksPassword(proxyPass);

        // 创建一个ChromeOptions对象,用于设置Chrome浏览器的选项

        ChromeOptions options = new ChromeOptions();

        // 使用setProxy方法来指定代理信息

        options.setProxy(proxy);

        // 创建一个WebDriver对象,用于控制Chrome浏览器,并传入options参数

        WebDriver driver = new ChromeDriver(options);

        // 添加一个隐式等待,用于等待页面元素加载完成

        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

        // 使用get方法来打开抖音网页版首页

        driver.get("https://www.douyin.com/");

        // 使用findElement方法,根据id属性,找到搜索框元素,并使用sendKeys方法输入关键词“猫”

        WebElement searchBox = driver.findElement(By.id("search-input"));

        searchBox.sendKeys("猫");

        // 使用findElement方法,根据class属性,找到搜索按钮元素,并使用click方法点击搜索

        WebElement searchButton = driver.findElement(By.className("search-btn"));

        searchButton.click();

        // 使用findElements方法,根据class属性,找到所有的视频列表元素,并存入一个List中

        List<WebElement> videoList = driver.findElements(By.className("video-card"));

        // 创建一个List对象,用于存储每个视频的信息

        List<VideoInfo> videoInfoList = new ArrayList<>();

        // 遍历每个视频元素,获取其标题、作者、点赞数、评论数等信息,并创建一个VideoInfo对象,并添加到videoInfoList中

        for (WebElement video : videoList) {

            // 获取视频标题

            String title = video.findElement(By.className("video-card-title")).getText();

            // 获取视频作者

            String author = video.findElement(By.className("video-card-user-name")).getText();

            // 获取视频点赞数

            String likes = video.findElement(By.className("video-card-like-count")).getText();

            // 获取视频评论数

            String comments = video.findElement(By.className("video-card-comment-count")).getText();

            // 创建一个VideoInfo对象,并设置相应的属性

            VideoInfo videoInfo = new VideoInfo();

            videoInfo.setTitle(title);

            videoInfo.setAuthor(author);

            videoInfo.setLikes(likes);

            videoInfo.setComments(comments);

            // 将VideoInfo对象添加到videoInfoList中

            videoInfoList.add(videoInfo);

        }

        // 创建一个Workbook对象,用于表示一个Excel文件,并使用XSSFWorkbook类来创建一个xlsx格式的文件

        Workbook workbook = new XSSFWorkbook();

        // 创建一个Sheet对象,用于表示一个工作表,并命名为“抖音视频”

        Sheet sheet = workbook.createSheet("抖音视频");

        // 在Sheet对象中创建第一行,并设置单元格的值为标题、作者、点赞数、评论数等字段名

        Row headerRow = sheet.createRow(0);

        headerRow.createCell(0).setCellValue("标题");

        headerRow.createCell(1).setCellValue("作者");

        headerRow.createCell(2).setCellValue("点赞数");

        headerRow.createCell(3).setCellValue("评论数");

        // 在Sheet对象中创建后续的行,并根据videoInfoList中的数据,设置单元格的值为对应的视频信息

        for (int i = 0; i < videoInfoList.size(); i++) {

            // 获取第i个VideoInfo对象

            VideoInfo videoInfo = videoInfoList.get(i);

            // 在Sheet对象中创建第i+1行

            Row row = sheet.createRow(i + 1);

            // 设置单元格的值为VideoInfo对象的属性值

            row.createCell(0).setCellValue(videoInfo.getTitle());

            row.createCell(1).setCellValue(videoInfo.getAuthor());

            row.createCell(2).setCellValue(videoInfo.getLikes());

            row.createCell(3).setCellValue(videoInfo.getComments());

        }

        // 使用FileOutputStream对象,将Workbook对象写入到一个指定的文件中,并关闭流

        FileOutputStream fileOut = new FileOutputStream("douyin.xlsx");

        workbook.write(fileOut);

        fileOut.close();

        // 关闭浏览器

        driver.quit();

    }

}

// 定义一个VideoInfo类,用于封装视频信息

class VideoInfo {

    private String title; // 标题

    private String author; // 作者

    private String likes; // 点赞数

    private String comments; // 评论数

    public VideoInfo() {

    }

    public VideoInfo(String title, String author, String likes, String comments) {

        this.title = title;

        this.author = author;

        this.likes = likes;

        this.comments = comments;

    }

    public String getTitle() {

        return title;

    }

    public void setTitle(String title) {

        this.title = title;

    }

    public String getAuthor() {

        return author;

    }

    public void setAuthor(String author) {

        this.author = author;

    }

    public String getLikes() {

        return likes;

    }

    public void setLikes(String likes) {

        this.likes = likes;

    }

    public String getComments() {

        return comments;

    }

    public void setComments(String comments) {

        this.comments = comments;

    }

}

```

代码说明

- 导入Apache POI的Java库,用于操作Excel文件

- 在WebDriver对象创建后,添加一个隐式等待,用于等待页面元素加载完成

- 使用WebDriver对象的findElement方法,根据元素的id或class属性,找到搜索框和搜索按钮,并使用sendKeys和click方法,输入关键词并点击搜索

- 使用WebDriver对象的findElements方法,根据元素的class属性,找到所有的视频列表,并遍历每个视频,获取其标题、作者、点赞数、评论数等信息,并存入一个List中

- 创建一个Workbook对象,用于表示一个Excel文件,并创建一个Sheet对象,用于表示一个工作表

- 在Sheet对象中创建第一行,并设置单元格的值为标题、作者、点赞数、评论数等字段名

- 在Sheet对象中创建后续的行,并根据List中的数据,设置单元格的值为对应的视频信息

- 使用FileOutputStream对象,将Workbook对象写入到一个指定的文件中

总结

本文介绍了如何在Selenium中使用Chrome浏览器,并且设置代理服务器来避免被目标网站识别。运行上述代码,可以看到Chrome浏览器自动打开www.douyin.com,并且将视频的标题、作者、点赞数、评论数等信息存入文件,这说明我们成功地访问目标网站。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容