几年前,我正在忙于一些工作,客户希望了解如何解决现实世界中的问题。 他们要求我自动化woot.com网站上的某些任务。

他们的任务是访问各个网站,并阅读当天商品的名称和价格。

我写了一些Selenium代码,以为可以将其张贴在这里,以防任何对任何人有用。

我得到了这份工作,所以这不会太糟糕。

首先,我定义了一个界面来表示一个woot页面:

package uk.co.doogle;import com.thoughtworks.selenium.Selenium;/*** This interface defines the methods we must implement for classes* of type Woot. Woot web sites have one item for sale every 24 hours.* @author Tony*/public interface Woot {/*** Defines the interface of the method we use to get the price* of the item for sale on a Woot website* @param selenium the selenium object we pass in which is used to interact* with the browser/web page* @return String representation of the price of the item for sale*/public String getPrice(Selenium selenium);/*** Defines the interface of the method we use to get the product name* of the item for sale on a Woot website* @param selenium the selenium object we pass in which is used to interact* with the browser/web page* @return String representation of the product name of the item for sale*/public String getProductName(Selenium selenium);}

然后,我多次实现了此接口,以表示各种woot页面的实际行为–例如,如果是winewoot页面:

public class WineWoot extends BaseWoot {/*** Constructor* @param url pass in the url of the web site*/public WineWoot(String url) {super(url);}/*** Implementation of the method to get the price of the object for sale on* the Woot web site.*/public String getPrice(Selenium selenium) {//if you need to update the xpath to the piece of text of interest - use xpather firefox pluginString xPath = '//html/body/header/nav/ul/li[8]/section/div/a/div[3]/span';selenium.waitForCondition('selenium.isElementPresent(\'xpath=' + xPath + '\');', '12000');return selenium.getText(xPath) + ' ';}/*** Implementation of the method to get the product name of the item for sale* on the Woot web site**/public String getProductName(Selenium selenium) {//if you need to update the xpath to the piece of text of interest - use xpather firefox pluginString xPath = '//html/body/header/nav/ul/li[8]/section/div/a/div[2]';selenium.waitForCondition('selenium.isElementPresent(\'xpath=' + xPath + '\');', '12000');return selenium.getText(xPath) + ' ';}}

注意–当时我使用了xPather插件–对于最新版本的firefox无效,因此现在我使用firebug 。

然后我写了实际的“测试”:

package uk.co.doogle;import com.thoughtworks.selenium.*;import java.io.BufferedWriter;import java.io.FileWriter;import java.util.ArrayList;import java.util.List;/*** This class is where we define tests of the Woot web sites* @author Tony**/public class TestWoots extends SeleneseTestCase {/*** Outputstream for our results file*/private BufferedWriter out;/*** Our list of Woot web sites we want to test*/private List<BaseWoot> sites = new ArrayList<BaseWoot>();/*** This is where we do any set up needed before our test(s) run.* Here we add the list of Woot web sites we want to test and we create an* output stream ready to write results to file*/public void setUp() throws Exception {sites.add(new BaseWoot('http://www.woot.com/'));sites.add(new ShirtWoot('http://shirt.woot.com/'));sites.add(new WineWoot('http://wine.woot.com/'));try {//let's append to our file...FileWriter fstream = new FileWriter('out.csv', true);out = new BufferedWriter(fstream);out.write('Site, Product Name, Product Price');out.newLine();} catch (Exception e) {System.err.println('Error creating a file to write our results to: ' + e.getMessage());}}/*** Tests getting the item name and price for the item for sale on each Woot web site we test. We see the results of the test* in std out in the form of a table and we also write the results to a csv file.* If there are any errors getting the information, this is displayed instead.** How to run me: open command prompt and from the directory where our selenium server is* located type: java -jar selenium-server-standalone-2.0b3.jar (or equivalent) and wait for the server to start up.* Then just run this unit test.*/public void testGetItemsAndPrices() throws Exception {//for each Woot site in our list of sites we want to testfor (BaseWoot woot : sites) {//let's put this in a try catch block as we want to try ALL the sites - some may be down or slow...try {selenium = new DefaultSelenium('localhost', 4444, '*firefox', woot.getUrl());selenium.start();selenium.open('/');selenium.waitForPageToLoad('50000');//add a new row for our table to std outSystem.out.println();//print out the information we need - the site, the title of the item for sale and the priceString siteUrl = woot.getUrl();String productName = woot.getProductName(selenium);String productPrice = woot.getPrice(selenium);//sometimes there are commas which mess up our csv file - so//we substitute with ;productName = productName.replace(',', ';');System.out.print('website: ' + siteUrl + ' ');System.out.print('product name: ' + productName);System.out.print('price: ' + productPrice);out.write(siteUrl + ', ' + productName + ', ' + productPrice);out.newLine();} catch (Exception ex) {//here may may see that the web site under test has changed and the xpath to the price or product name may need to//be changed in the Woot classSystem.out.print('problem getting the data for: ' + woot.getUrl()+ ' ' + ex.getMessage() + ' ');} finally {selenium.stop();}}}/*** Any tear-down we need to do to cleanup after our test(s).* Here we just stop selenium and close the output stream*/public void tearDown() throws Exception {selenium.stop();out.close();}}

我知道这段代码已经使用了几年,并且我做了一些小的改动以使其能够与当前的woot.com网站一起使用-我要做的就是为其获取最新的selenium-server-standalone.jar 。与最新的Firefox一起使用,还可以将xpath更新为价格和产品名称信息。 这将是对代码的一个很好的改进-使它成为数据驱动的-这样我们就可以只更新配置文件中的xpath,而无需更改我在这里使用的硬编码文件。 那实际上是来自客户的唯一反馈。

参考:来自Doogle Ltd博客的JCG合作伙伴 Tony Dugay的Java Selenium / WebDriver示例 。

翻译自: https://www.javacodegeeks.com/2012/12/a-seleniumwebdriver-example-in-java.html

Java中的Selenium / WebDriver示例相关推荐

  1. Java中的Volatile如何工作? Java中的volatile关键字示例

    如何在Java中使用Volatile关键字 在Java采访中,什么是volatile变量以及何时在Java中使用volatile变量是Java 采访中一个著名的多线程采访问题 . 尽管许多程序员都知道 ...

  2. java cursor_使用3.0驱动程序的Java中的Tailable Cursor示例?

    有人可以在 Java中提供完整的tailable游标示例吗?我使用3.0驱动程序,所有示例似乎是2.x.我的classpath中只有mongo-java-driver-3.0.0.jar.我希望得到所 ...

  3. java 线性回归算法_线性搜索或顺序搜索算法在Java中如何工作? 示例教程

    java 线性回归算法 大家好,之前,我讨论了二进制搜索算法的工作原理,并分享了在Java中实现二进制搜索的代码. 在那篇文章中,有人问我是否还有其他搜索算法? 如果数组中的元素未排序,又该如何使用它 ...

  4. java jsoup解析_3使用Jsoup解析Java中HTML文件的示例

    java jsoup解析 HTML是Web的核心,无论您是通过JavaScript,JSP,PHP,ASP或任何其他Web技术动态生成的,您在Internet上看到的所有页面都是基于HTML的. 您的 ...

  5. 线性搜索或顺序搜索算法在Java中如何工作? 示例教程

    大家好,我之前谈到了二进制搜索算法的工作原理,并分享了在Java中实现二进制搜索的代码. 在那篇文章中,有人问我是否还存在其他搜索算法? 如果数组中的元素未排序,又如何使用二进制搜索算法,该如何搜索呢 ...

  6. 3使用Jsoup解析Java中HTML文件的示例

    HTML是Web的核心,无论您是通过JavaScript,JSP,PHP,ASP还是任何其他Web技术动态生成的,您在Internet上看到的所有页面都是基于HTML的. 您的浏览器实际上是解析HTM ...

  7. Java中的状态设计模式–示例教程

    状态模式是行为设计模式之一 . 当对象根据其内部状态更改其行为时,将使用状态设计模式. 如果必须根据对象的状态更改其行为,则可以在对象中使用状态变量,并使用if-else条件块根据状态执行不同的操作. ...

  8. Java中的Memento设计模式-示例教程

    记忆模式是行为设计模式之一 . 当我们要保存对象的状态以便以后可以恢复时,可以使用Memento设计模式. 记忆模式用于以这种方式实现该目的,即在对象外部无法访问该对象的已保存状态数据,从而保护了已保 ...

  9. Java中的访问者设计模式–示例教程

    访客模式是行为设计模式之一 . 当我们必须对一组相似类型的对象执行操作时,将使用访问者模式. 借助访问者模式,我们可以将操作逻辑从对象移动到另一个类. 例如,假设有一个购物车,我们可以在其中添加不同类 ...

最新文章

  1. tomcat服务器两个端口配置两个项目,Tomcat 7通过设置不同的端口部署两个项目
  2. python学习-16 列表list
  3. ngx_timeofday,定时器管理
  4. 模拟滤波器的单位冲激响应+单位阶跃响应+斜坡响应+抛物线响应matlab实现(转载+整理)
  5. Java高级篇(二)——网络通信
  6. CPU缓存越大计算机的性能越好,CPU缓存真的越大越好?小心你的钱包
  7. RegOpenKeyEx 返回值 2
  8. * IO流递归拷贝一个文件夹 按源文件夹格式拷贝
  9. 多态计算器的开发 c# 1614095334
  10. nginx 日志格式设置 和 负载均衡下 获取真实ip
  11. VS11中添加PagedList引用
  12. 了解一些FMS的基本概念
  13. python许可证过期_x-pack许可证过期问题解决
  14. 【转】详解4G内存与CPU,BIOS和操作系统之间的牵绊
  15. Python数据分析案例08——预测泰坦尼克号乘员的生存(机器学习全流程)
  16. 一种繁体ppt转换简体的方法(简转繁同样适用)
  17. c语言十进制转ieee754代码,C#IEEE754到十进制(C# IEEE754 to decimal)
  18. C#使用iTextSharp合并pdf,添加页码
  19. 抓起整个网站离线浏览的软件Teleport Pro
  20. 高科技公司全线受损 中国电子企业盼政府救市

热门文章

  1. MySQL导入冲突保留两者_面试被问MySQL 主从复制,怎么破?
  2. python找不到指定的文件夹里_Python环球网在Unix中的指定文件路径中找不到*.txt
  3. 以Linux系统(Ubuntu)开发生活(一)
  4. Mac 环境变量配置
  5. 实现模糊查询并忽略大小写
  6. HttpClient 4 API –获取状态代码-getStatusLine()。getStatusCode()示例
  7. 自动部署 管道 ci cd_自动化测试在CI CD管道中的作用
  8. java fix_Java中的低延迟FIX引擎
  9. app访问java web_Java Web App体系结构
  10. maven将第三方依赖_如何将商业第三方文物整合到您的Maven版本中