Java中的Selenium / WebDriver示例
幾年前,我正在忙于一些工作,客戶希望了解如何解決現實世界中的問題。 他們要求我自動化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示例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 台式电脑屏幕亮度调节方法台式电脑如何调节
- 下一篇: Java ByteBuffer –速成课