selenium-java自动化教程

文章目录

    • Selenium
      • 支持语言
      • WebDriver
    • 开始使用
      • chromedriver
      • 模拟用户浏览访问
      • 模拟点击事件
        • 关闭弹窗,选中元素并点击
      • 获取页面文本
      • 结语

Selenium

 Selenium是一个自动化测试工具,可以模拟用户操作web端浏览器的行为,包括点击、输入、选择等。也可以获取交互界面上的指定元素的内的数据,也就是爬虫。

支持语言

  Selenium支持Java、Python、CSharp、Ruby、JavaScript、Kotlin,对于会java语言的,可以直接使用selenium-java

WebDriver

 Selenium 的核心是 WebDriver,这是一个编写指令集的接口,可以在许多浏览器运行。我们要在浏览器中模拟用户点击就需要一个对应的驱动组件来实现这个功能,WebDriver就是以原生的方式驱动浏览器,就像用户在本地操作浏览器一样。
在这里插入图片描述

开始使用

chromedriver

 上边说了我们要驱动浏览器做一些行为动作就需要一个对应的驱动,目前支持的浏览器有:Firefox、Chrome、Edge、IE、Apple Safari,下面我们使用Chrome浏览器
chromedriver
chromedriver125.0.6422.141稳定版
我使用的浏览器版本是125.0.6422.142,小版本差别影响不大 可以直接使用,下载的WebDriver如果版本差别太大启动的时候会提示浏览器版本不支持。

在这里插入图片描述

模拟用户浏览访问

 以模拟用户浏览页面,不断的滚动页面直到最底部这样一个需求,下面开始编码

<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId><version>2.6.0</version></dependency><dependency><groupId>org.seleniumhq.selenium</groupId><artifactId>selenium-java</artifactId><version>3.141.59</version></dependency>
</dependencies>
@Component
public class BlogService {private final List<String> UA_LIST = Arrays.asList("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.0.0 Safari/537.36","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.0.0 Safari/537.36","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.0.0 Safari/537.36","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.0.0 Safari/537.36","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.0.0 Safari/537.36","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.0.0 Safari/537.36","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.0.0 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.0.0 Safari/537.36");// 要访问的页面地址private final List<String> URL_LIST = Arrays.asList("https://wiki.mbalib.com/wiki/%E7%BB%B4%E5%9F%BA%E7%99%BE%E7%A7%91");private final AtomicInteger count = new AtomicInteger();public static void main(String[] args) {// websiteTask();}private void websiteTask() {System.setProperty(FirefoxDriver.SystemProperty.BROWSER_LOGFILE, "/dev/null");// driver驱动下载地址:https://googlechromelabs.github.io/chrome-for-testing/System.setProperty("webdriver.chrome.driver", "src\\main\\resources\\125\\chromedriver.exe");   //设置chrome驱动程序的路径System.out.println(System.getProperty("webdriver.chrome.driver"));ChromeOptions opt = new ChromeOptions();//opt.addArguments("-headless");     // 开启无界面模式opt.addArguments("--disable-gpu");  // 禁用gpuopt.addArguments("--user-agent=" + getRandom(UA_LIST));WebDriver driver = new ChromeDriver(opt);   //初始化一个chrome驱动实例,保存到driver中try {// driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); //隐式等待10秒//最大化窗口driver.manage().window().maximize();  //最大化窗口driver.get(getRandom(URL_LIST));Thread.sleep(1000);  // 等待页面加载xs// 强制转换WebDriver为JavascriptExecutorJavascriptExecutor jsExecutor = (JavascriptExecutor) driver;// 执行JavaScript代码来获取页面的滚动条高度int scrollHeight = Integer.parseInt(jsExecutor.executeScript("return document.documentElement.scrollHeight;").toString());// 可以根据滚动条高度,每次滚动多少px,计算出总共需要滚动多少次,这样就可以滚动到最底部int num = scrollHeight / 400;for (int i = 0; i < num; i++) {int height = (i + 1) * 400;((JavascriptExecutor) driver).executeScript("window.scrollTo({" + "top: " + height + ",behavior: \"smooth\"" + "})");Thread.sleep(1000);  // 每次滚动等待一定时间}} catch (Exception e) {e.printStackTrace();} finally {driver.manage().deleteAllCookies();System.out.println("当前第几次:" + count.incrementAndGet() + " , 打开页面的标题是: " + driver.getTitle());//关闭并退出浏览器driver.quit();}}/*** 随机获取一个地址*/private String getRandom(List<String> list) {// shuffle 打乱顺序Collections.shuffle(list);return list.get(0);}// initialDelay:第一次延迟多长时间后再执行, fixedRate:之后按fixedRate的规则每x秒执行一次@Scheduled(initialDelay = 0, fixedRate = 13000)public void timingTask() {System.out.println("start task........");websiteTask();}
}

运行效果:

selenium-java模拟浏览页面

模拟点击事件

使用这个网站作为示例:测试页面

在这里插入图片描述

由于打开页面有一个提示框,需要先把提示框关闭后才可以对页面元素进行操作,否则会提示元素是不可点击的。
所以我们的步骤是:先打开页面 选中弹窗右上角的关闭图标点击它,然后才能选择页面上要操作的元素。

关闭弹窗,选中元素并点击

 使用xpath语法和浏览器插件可以非常方便的选中要操作的元素,然后在代码中获取到这个元素并调用它的点击事件

@Component
public class BlogService {private final List<String> UA_LIST = Arrays.asList("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.0.0 Safari/537.36","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.0.0 Safari/537.36","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.0.0 Safari/537.36","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.0.0 Safari/537.36","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.0.0 Safari/537.36","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.0.0 Safari/537.36","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.0.0 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.0.0 Safari/537.36");// 要访问的页面地址private final List<String> URL_LIST = Arrays.asList("https://wiki.mbalib.com/wiki/%E7%BB%B4%E5%9F%BA%E7%99%BE%E7%A7%91");private final AtomicInteger count = new AtomicInteger();public static void main(String[] args) {// websiteTask();}private void websiteTask() {System.setProperty(FirefoxDriver.SystemProperty.BROWSER_LOGFILE, "/dev/null");// driver驱动下载地址:https://googlechromelabs.github.io/chrome-for-testing/System.setProperty("webdriver.chrome.driver", "src\\main\\resources\\125\\chromedriver.exe");   //设置chrome驱动程序的路径System.out.println(System.getProperty("webdriver.chrome.driver"));ChromeOptions opt = new ChromeOptions();//opt.addArguments("-headless");     // 开启无界面模式opt.addArguments("--disable-gpu");  // 禁用gpuopt.addArguments("--user-agent=" + getRandom(UA_LIST));WebDriver driver = new ChromeDriver(opt);   //初始化一个chrome驱动实例,保存到driver中try {// driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); //隐式等待10秒//最大化窗口driver.manage().window().maximize();  //最大化窗口driver.get(getRandom(URL_LIST));Thread.sleep(1000);  // 等待页面加载xs// 先关闭弹窗String headExpression = "//div[@class=\"bg hid\" and @id=\"vip_popup_img\"]//*[local-name() = \"svg\" and @class=\"head-icon\"]";WebElement headElement = driver.findElement(By.xpath(headExpression));headElement.click();//再操作页面元素String xpathExpression = "//div[@id=\"globalWrapper\"]/div[@id=\"column-content\"]/div[3]/div[@id=\"bodyContent\"]/dl[1]//a[3]";WebElement element = driver.findElement(By.xpath(xpathExpression));// 模拟点击事件element.click();Thread.sleep(10000);} catch (Exception e) {e.printStackTrace();} finally {driver.manage().deleteAllCookies();System.out.println("当前第几次:" + count.incrementAndGet() + " , 打开页面的标题是: " + driver.getTitle());//关闭并退出浏览器driver.quit();}}/*** 随机获取一个地址*/private String getRandom(List<String> list) {// shuffle 打乱顺序Collections.shuffle(list);return list.get(0);}// initialDelay:第一次延迟多长时间后再执行, fixedRate:之后按fixedRate的规则每x秒执行一次@Scheduled(initialDelay = 0, fixedRate = 13000)public void timingTask() {System.out.println("start task........");websiteTask();}
}

运行效果:

selenium-java模拟点击按钮事件

获取页面文本

 如果页面有很多文本文字,要获取(paqu)页面的文字内容也非常的简单
在这里插入图片描述

String xpathExpression = "//div[@id=\"content\"]/div[@id=\"bodyContent\"]//p[1]";
WebElement element = driver.findElement(By.xpath(xpathExpression));
System.out.println(element.getText());

结语

 xpath语法网络上很多资料这里就不做具体介绍了,主要说一下paqu数据的主要步骤,通过xpath可以获取到指定元素的文本内容、模拟元素的点击事件,这样我们就可以实现paqu网页数据,如果页面有分页的话也可以通过编写代码的方式获取到所有数据

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/diannao/25133.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

深入理解Python:装饰器与闭包

深入理解Python:装饰器与闭包 在Python编程中,装饰器和闭包是两个非常有用的高级特性。装饰器允许我们在不修改函数或类定义的情况下扩展其功能,而闭包则使得函数能够捕获和保存其所在作用域的变量。本文将详细介绍装饰器和闭包的基本概念、使用方法以及它们在实际应用中的…

系统运行中数据库瓶颈的解决方案

数据库在系统运行中的重要性不言而喻。它不仅是数据存储的核心&#xff0c;更是数据操作和管理的枢纽。然而&#xff0c;随着系统的逐步扩展&#xff0c;数据库的性能瓶颈问题常常成为阻碍系统高效运行的瓶颈。本文将探讨在系统运行中&#xff0c;当数据库遇到瓶颈时的解决方案…

Linux---进程/磁盘管理

文章目录 目录 文章目录 一.Linux中进程的概念 二.显示系统执行的进程 2.1: ps 命令 2.2 top 命令 三.终止进程 四.磁盘分区 一.Linux中进程的概念 在Linux中&#xff0c;进程是指操作系统中正在执行的程序的实例。每个进程都由操作系统分配了独立的内存空间&#xff0c;用于…

共识算法之争(PBFT,Raft,PoW,PoS,DPoS)

文章目录 共识算法拜占庭容错技术&#xff08;Byzantine Fault Tolerance&#xff0c;BFT&#xff09;PBFT&#xff1a;Practical Byzantine Fault Tolerance&#xff0c;实用拜占庭容错算法Raft协议POW(Proof of Work)工作量证明机制POSDPoS&#xff08;Delegated Proof of St…

多关键字排序

成绩排序 查看测评数据信息 给出班里某门课程的成绩单&#xff0c;请你按成绩从高到低对成绩单排序输出&#xff0c;如果有相同分数则名字字典序小的在前。 输入格式 第一行为n (0 < n < 20)&#xff0c;表示班里的学生数目&#xff1b; 接下来的n行&#xff0c;每行为每…

[创业之路-115] :互联网时代的创客文化与创客文化在企业中的应用

目录 一、什么是创客文化 》美国人的文化基因 1.1、创客文化的起源与发展 1.2、创客文化的特点 1.3、创客文化的应用与价值 1.4、创客文化的挑战与解决方案 二、创业文化对新职场人思维方式的转变 》美国人的文化基因 2.1、从固定思维到创新思维 2.2、从单打独斗到团队…

08-Eureka-eureka原理分析

08-Eureka-eureka原理分析 1.服务调用出现的问题: 1.服务消费者该如何获取服务提供者的地址信息? 2.如果有多个服务提供者,消费者该如何选择? 3.消费者如何得知服务提供者的健康状态? 2.Eureka的作用(原理): 在Eureka的结构当中,他分成了两个概念,两个角色。第…

LNWT--篇章三小测

问题1: BERT训练时候的学习率learning rate如何设置? 在训练初期使用较小的学习率&#xff08;从 0 开始&#xff09;&#xff0c;在一定步数&#xff08;比如 1000 步&#xff09;内逐渐提高到正常大小&#xff08;比如上面的 2e-5&#xff09;&#xff0c;避免模型过早进入…

Lua 元表(Metatable)深入解析

Lua 元表&#xff08;Metatable&#xff09;深入解析 Lua 是一种轻量级的编程语言&#xff0c;因其简洁性和强大的扩展能力而被广泛应用于游戏开发、脚本编写和其他领域。在 Lua 中&#xff0c;元表&#xff08;Metatable&#xff09;是一个非常重要的概念&#xff0c;它允许我…

hexo更新流程及解析

文章目录 文件解析md文件头部内容&#xff08;1&#xff09;文章顶置&#xff0c;排序&#xff08;2&#xff09;文章隐藏&#xff08;3&#xff09;分类和标签&#xff08;4&#xff09;其他属性 更新博客注意安装插件注意&#xff1a;1、关于中括号的问题 文件解析 . ├──…

【Redis】Redis实现分布式锁合理的控制锁的有效时长的方法

在分布式系统中&#xff0c;合理地控制 Redis 分布式锁的有效时长&#xff08;即过期时间&#xff09;非常重要&#xff0c;以确保锁既能防止死锁又能提供高可用性。设置合理的过期时间可以防止客户端在持有锁期间崩溃而导致其他客户端无法获取锁的情况&#xff0c;同时也能确保…

[数据集][目标检测]足球场足球运动员身份识别足球裁判员数据集VOC+YOLO格式312张4类别

数据集格式&#xff1a;Pascal VOC格式YOLO格式(不包含分割路径的txt文件&#xff0c;仅仅包含jpg图片以及对应的VOC格式xml文件和yolo格式txt文件) 图片数量(jpg文件个数)&#xff1a;312 标注数量(xml文件个数)&#xff1a;312 标注数量(txt文件个数)&#xff1a;312 标注类别…

调查显示各公司在 IT 安全培训方面存在差距

网络安全提供商 Hornetsecurity 最近进行的一项调查显示&#xff0c;许多组织的 IT 安全培训存在严重缺陷。 这项调查是在伦敦举行的 Infosecurity Europe 2024 期间发布的&#xff0c;调查发现 26% 的组织没有为其最终用户提供任何 IT 安全培训。 这些调查结果来自世界各地的…

阿里云活动推荐:AI 应用 DevOps 新体验

活动简介 阿里云新活动&#xff0c;体验阿里云的云效应用交付平台。体验了下&#xff0c;总体感觉还不错。平台把常规的开发过程封装成了模板&#xff0c;部署发布基本都是一键式操作&#xff0c;并且对自定义支持的比较好。 如果考虑将发布和部署搬到云上&#xff0c;可以玩一…

代码随想录算法训练营DAY32|122.买卖股票的最佳时机II、55. 跳跃游戏、45.跳跃游戏II

122.买卖股票的最佳时机II 题目链接&#xff1a;122.买卖股票的最佳时机II class Solution(object):def maxProfit(self, prices):""":type prices: List[int]:rtype: int"""max_profit 0profit 0buyin_idx 0for i in range(len(prices)):p…

力扣第185题:部门工资前三高的员工

关注微信公众号 数据分析螺丝钉 免费领取价值万元的python/java/商业分析/数据结构与算法学习资料 在本篇文章中&#xff0c;我们将详细解读力扣第185题“部门工资前三高的员工”。通过学习本篇文章&#xff0c;读者将掌握如何使用SQL语句来解决这一问题&#xff0c;并了解相关…

使用selenium/drissionpage时如何阻止chrome自动跳转http到https

加个启动参数&#xff1a; --allow-running-insecure-content没了 参考文章&#xff1a;List of Chromium Command Line Switches

Directory Opus 13.6 可用的apk文件右键菜单脚本

// apk文件的右键经过adb安装的脚本,可以在多个设备中选择function OnClick(clickData) {try {// 检查是否选中了文件if (clickData.func.sourcetab.selected_files.count 0) {DOpus.Output("没有选中任何文件");return;}// 获取选中的文件名var selectedFile clic…

JSTL知识点讲解与配置

JSTL&#xff08;JavaServer Pages Standard Tag Library&#xff09;是Java EE平台中的一个标准库&#xff0c;提供了一组用于在JSP&#xff08;JavaServer Pages&#xff09;中简化和标准化常见任务的标签。这些标签封装了很多常见的JSP功能&#xff0c;可以使得JSP页面更加简…

18-Nacos-NacosRule负载均衡

18-Nacos-NacosRule负载均衡 1.根据集群负载均衡 1.修改order-service中的application.yml,设置集群为HZ: spring:cloud:nacos:server-addr: localhost:8848 #nacos服务端地址discovery:cluster-name: HZ #配置集群名,也就是机房位置,例如:HZ,杭州2.然后在order-servi…