Пару лет назад я собирался поработать, и клиент хотел посмотреть, как я буду решать реальные проблемы. Они попросили меня автоматизировать некоторые задачи на веб-сайте woot.com.
Задача состояла в том, чтобы зайти на различные веб-сайты woot и прочитать название продукта и цену предложения дня.
Я написал немного кода Selenium и решил опубликовать его здесь на тот случай, если он пригодится кому-либо.
Я получил работу — так что это не может быть слишком плохо.
Сначала я определил интерфейс для представления страницы woot:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
|
<span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" > package uk.co.doogle;</span> пакет uk.co.doogle;</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" > import com.thoughtworks.selenium.Selenium;</span> импорт com.thoughtworks.selenium.Selenium;</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" > /**</span> / **</span> <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">* This interface defines the methods we must implement for classes</span> * Этот интерфейс определяет методы, которые мы должны реализовать для классов</span> <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">* of type Woot.</span> * типа Woot.</span> <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">Woot web sites have one item for sale every 24 hours.</span> На веб-сайтах Woot есть один предмет на продажу каждые 24 часа.</span> <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">* @author Tony</span> * @author Tony</span> <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">*/ </span> * /</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" > public interface Woot {</span> публичный интерфейс Woot {</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" > /**</span> / **</span> <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">* Defines the interface of the method we use to get the price</span> * Определяет интерфейс метода, который мы используем, чтобы получить цену</span> <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">* of the item for sale on a Woot website</span> * предмета для продажи на сайте Woot</span> <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">* @param selenium the selenium object we pass in which is used to interact</span> * @param selenium объект селена, который мы передаем, используется для взаимодействия</span> <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">* with the browser/web page</span> * с браузером / веб-страницей</span> <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">* @return String representation of the price of the item for sale</span> * @return Строковое представление цены товара на продажу</span> <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">*/ </span> * /</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" > public String getPrice(Selenium selenium);</span> public String getPrice (селен селена);</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" > /**</span> / **</span> <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">* Defines the interface of the method we use to get the product name</span> * Определяет интерфейс метода, который мы используем, чтобы получить название продукта</span> <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">* of the item for sale on a Woot website</span> * предмета для продажи на сайте Woot</span> <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">* @param selenium the selenium object we pass in which is used to interact</span> * @param selenium объект селена, который мы передаем, используется для взаимодействия</span> <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">* with the browser/web page</span> * с браузером / веб-страницей</span> <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">* @return String representation of the product name of the item for sale</span> * @return Строковое представление названия товара предмета для продажи</span> <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">*/ </span> * /</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" > public String getProductName(Selenium selenium);</span> public String getProductName (селен селена);</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" >}</span> }</span> |
Затем я реализовал этот интерфейс несколько раз, чтобы представить реальное поведение различных страниц woot — вот, например, страница winewoot:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
|
<span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" > public class WineWoot extends BaseWoot {</span> открытый класс WineWoot расширяет BaseWoot {</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" > /**</span> / **</span> <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">* Constructor</span> * Конструктор</span> <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">* @param url pass in the url of the web site</span> * @param url pass в URL веб-сайта</span> <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">*/ </span> * /</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" > public WineWoot(String url) {</span> public WineWoot (String url) {</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" > super (url);</span> супер (URL);</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" >}</span> }</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" > /**</span> / **</span> <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">* Implementation of the method to get the price of the object for sale on</span> * Реализация метода получения цены объекта на продажу по</span> <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">* the Woot web site.</span> * Веб-сайт Woot.</span> <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">*/ </span> * /</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" > public String getPrice(Selenium selenium) {</span> public String getPrice (селен селена) {</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" > //if you need to update the xpath to the piece of text of interest - use xpather firefox plugin</span> // если вам нужно обновить xpath на интересующий вас текст - используйте плагин xpather firefox</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" >String xPath = '//html/body/header/nav/ul/li[8]/section/div/a/div[3]/span' ;</span> String xPath = '// html / body / header / nav / ul / li [8] / section / div / a / div [3] / span' ;</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" >selenium.waitForCondition( 'selenium.isElementPresent(\'xpath=' + xPath + '\');' , '12000' );</span> selenium.waitForCondition ( 'selenium.isElementPresent (\' xpath = ' + xPath + ' \ ' ); ', ' 12000 ');</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" > return selenium.getText(xPath) + ' ' ;</span> return selenium.getText (xPath) + '' ;</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" >}</span> }</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" > /**</span> / **</span> <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">* Implementation of the method to get the product name of the item for sale</span> * Реализация метода получения наименования товара предмета для продажи</span> <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">* on the Woot web site</span> * на веб-сайте Woot</span> <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">*</span> *</span> <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">*/ </span> * /</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" > public String getProductName(Selenium selenium) {</span> public String getProductName (селен селена) {</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" > //if you need to update the xpath to the piece of text of interest - use xpather firefox plugin</span> // если вам нужно обновить xpath на интересующий вас текст - используйте плагин xpather firefox</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" >String xPath = '//html/body/header/nav/ul/li[8]/section/div/a/div[2]' ;</span> String xPath = '// html / body / header / nav / ul / li [8] / section / div / a / div [2]' ;</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" >selenium.waitForCondition( 'selenium.isElementPresent(\'xpath=' + xPath + '\');' , '12000' );</span> selenium.waitForCondition ( 'selenium.isElementPresent (\' xpath = ' + xPath + ' \ ' ); ', ' 12000 ');</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" > return selenium.getText(xPath) + ' ' ;</span> return selenium.getText (xPath) + '' ;</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" >}</span> }</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" >}</span> }</span> |
Обратите внимание — тогда я использовал плагин xPather — это не работает для последних версий Firefox, поэтому теперь я использую Firebug .
Затем я написал настоящий «тест»:
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
|
<span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" > package uk.co.doogle;</span> пакет uk.co.doogle;</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" > import com.thoughtworks.selenium.*;</span> импорт com.thoughtworks.selenium. *;</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" > import java.io.BufferedWriter;</span> импорт java.io.BufferedWriter;</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" > import java.io.FileWriter;</span> import java.io.FileWriter;</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" > import java.util.ArrayList;</span> import java.util.ArrayList;</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" > import java.util.List;</span> import java.util.List;</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" > /**</span> / **</span> <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">* This class is where we define tests of the Woot web sites</span> * В этом классе мы определяем тесты веб-сайтов Woot</span> <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">* @author Tony</span> * @author Tony</span> <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">*</span> *</span> <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">*/ </span> * /</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" > public class TestWoots extends SeleneseTestCase {</span> открытый класс TestWoots extends SeleneseTestCase {</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" > /**</span> / **</span> <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">* Outputstream for our results file</span> * Outputstream для нашего файла результатов</span> <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">*/ </span> * /</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" > private BufferedWriter out;</span> приватный BufferedWriter out;</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" > /**</span> / **</span> <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">* Our list of Woot web sites we want to test</span> * Наш список веб-сайтов Woot, которые мы хотим протестировать</span> <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">*/ </span> * /</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" > private List<BaseWoot> sites = new ArrayList<BaseWoot>();</span> закрытый список <BaseWoot> сайтов = новый ArrayList <BaseWoot> ();</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" > /**</span> / **</span> <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">* This is where we do any set up needed before our test(s) run.</span> * Здесь мы выполняем любые необходимые настройки перед запуском нашего теста.</span> <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">* Here we add the list of Woot web sites we want to test and we create an</span> * Здесь мы добавляем список веб-сайтов Woot, которые мы хотим протестировать, и создаем</span> <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">* output stream ready to write results to file</span> * поток вывода готов записать результаты в файл</span> <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">*/ </span> * /</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" > public void setUp() throws Exception {</span> public void setUp () выдает Exception {</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" >sites.add( new BaseWoot( 'http://www.woot.com/' ));</span> sites.add (новый BaseWoot ( 'http://www.woot.com/' ));</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" >sites.add( new ShirtWoot( 'http://shirt.woot.com/' ));</span> sites.add (новый ShirtWoot ( 'http://shirt.woot.com/' ));</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" >sites.add( new WineWoot( 'http://wine.woot.com/' ));</span> sites.add (новый WineWoot ( 'http://wine.woot.com/' ));</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" > try {</span> пытаться {</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" > //let's append to our file...</span> // добавим в наш файл ...</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" >FileWriter fstream = new FileWriter( 'out.csv' , true );</span> FileWriter fstream = new FileWriter ( 'out.csv' , true );</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" >out = new BufferedWriter(fstream);</span> out = новый BufferedWriter (fstream);</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" >out.write( 'Site, Product Name, Product Price' );</span> out.write («Сайт, название продукта, цена продукта»);</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" >out.newLine();</span> out.newLine ();</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" >} catch (Exception e) {</span> } catch (исключение e) {</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" >System.err.println( 'Error creating a file to write our results to: ' + e.getMessage());</span> System.err.println ( 'Ошибка создания файла для записи наших результатов в:' + e.getMessage ());</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" >}</span> }</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" >}</span> }</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" > /**</span> / **</span> <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">* Tests getting the item name and price for the item for sale on each Woot web site we test.</span> * Проверяет получение имени и цены товара для продажи на каждом веб-сайте Woot, который мы тестируем.</span> <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">We see the results of the test</span> Видим результаты теста</span> <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">* in std out in the form of a table and we also write the results to a csv file.</span> * в стандартный вывод в виде таблицы, и мы также записываем результаты в CSV-файл.</span> <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">* If there are any errors getting the information, this is displayed instead.</span> * Если есть какие-либо ошибки при получении информации, это отображается вместо.</span> <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">*</span> *</span> <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">* How to run me: open command prompt and from the directory where our selenium server is</span> * Как запустить меня: откройте командную строку и из каталога, где находится наш сервер селена</span> <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">* located type: java -jar selenium-server-standalone-2.0b3.jar (or equivalent) and wait for the server to start up.</span> * расположен тип: java -jar selenium-server-standalone-2.0b3.jar (или эквивалентный) и дождитесь запуска сервера.</span> <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">* Then just run this unit test.</span> * Тогда просто запустите этот модульный тест.</span> <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">*/ </span> * /</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" > public void testGetItemsAndPrices() throws Exception {</span> public void testGetItemsAndPrices () создает исключение {</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" > //for each Woot site in our list of sites we want to test</span> // для каждого сайта Woot в нашем списке сайтов, которые мы хотим протестировать</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" > for (BaseWoot woot : sites) {</span> для (BaseWoot woot: sites) {</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" > //let's put this in a try catch block as we want to try ALL the sites - some may be down or slow...</span> // давайте поместим это в блок try catch, так как мы хотим попробовать ВСЕ сайты - некоторые могут работать медленно или медленно ...</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" > try {</span> пытаться {</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" >selenium = new DefaultSelenium( 'localhost' , 4444 , '*firefox' , woot.getUrl());</span> selenium = new DefaultSelenium ( 'localhost' , 4444 , '* firefox' , woot.getUrl ());</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" >selenium.start();</span> selenium.start ();</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" >selenium.open( '/' );</span> selenium.open ( '/' );</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" >selenium.waitForPageToLoad( '50000' );</span> selenium.waitForPageToLoad ( '50000' );</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" > //add a new row for our table to std out</span> // добавляем новую строку для нашей таблицы в std out</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" >System.out.println();</span> System.out.println ();</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" > //print out the information we need - the site, the title of the item for sale and the price</span> // распечатаем нужную нам информацию - сайт, название предмета для продажи и цену</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" >String siteUrl = woot.getUrl();</span> String siteUrl = woot.getUrl ();</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" >String productName = woot.getProductName(selenium);</span> String productName = woot.getProductName (селен);</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" >String productPrice = woot.getPrice(selenium);</span> String productPrice = woot.getPrice (селен);</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" > //sometimes there are commas which mess up our csv file - so</span> // иногда есть запятые, которые портят наш CSV-файл - так</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" > //we substitute with ;</span> // подставляем с помощью;</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" >productName = productName.replace( ',' , ';' );</span> productName = productName.replace ( ',' , ';' );</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" >System.out.print( 'website: ' + siteUrl + ' ' );</span> System.out.print ( 'website:' + siteUrl + '' );</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" >System.out.print( 'product name: ' + productName);</span> System.out.print ( 'имя продукта:' + productName);</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" >System.out.print( 'price: ' + productPrice);</span> System.out.print ( 'цена:' + productPrice);</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" >out.write(siteUrl + ', ' + productName + ', ' + productPrice);</span> out.write (siteUrl + ',' + productName + ',' + productPrice);</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" >out.newLine();</span> out.newLine ();</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" >} catch (Exception ex) {</span> } catch (Exex ex) {</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" > //here may may see that the web site under test has changed and the xpath to the price or product name may need to</span> // здесь может быть видно, что тестируемый веб-сайт изменился, и xpath к цене или названию продукта может потребоваться</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" > //be changed in the Woot class</span> // быть измененным в классе Woot</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" >System.out.print( 'problem getting the data for: ' + woot.getUrl()+ ' ' + ex.getMessage() + ' ' );</span> System.out.print ( 'проблема с получением данных для:' + woot.getUrl () + '' + ex.getMessage () + '' );</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" >} finally {</span> } наконец {</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" >selenium.stop();</span> selenium.stop ();</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" >}</span> }</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" >}</span> }</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" >}</span> }</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" > /**</span> / **</span> <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">* Any tear-down we need to do to cleanup after our test(s).</span> * Любой демонтаж, который мы должны сделать, чтобы очистить после наших тестов.</span> <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">* Here we just stop selenium and close the output stream</span> * Здесь мы просто останавливаем селен и закрываем выходной поток</span> <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">*/ </span> * /</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" > public void tearDown() throws Exception {</span> public void tearDown () генерирует исключение {</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" >selenium.stop();</span> selenium.stop ();</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" >out.close();</span> out.close ();</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" >}</span> }</span> <span class = "notranslate" onmouseover= "_tipon(this)" onmouseout= "_tipoff()" ><span class = "google-src-text" style= "direction: ltr; text-align: left" >}</span> }</span> |
Я знаю, что этот код работал в течение нескольких лет, и я внес некоторые незначительные изменения, чтобы заставить его работать с текущими веб-сайтами woot.com — все, что мне нужно было сделать, — это получить для него новейший selenium-server-standalone.jar работать с последним Firefox, а также обновлять xpath к информации о цене и названии продукта. Это было бы хорошим улучшением в коде — чтобы сделать его управляемым данными — таким образом, чтобы мы могли просто обновить xpaths в файле конфигурации, а не изменять жестко запрограммированные, которые я использовал здесь. Это был единственный отзыв от клиента на самом деле.
Ссылка: пример Selenium / WebDriver на Java от нашего партнера по JCG Тони Дугая из блога Doogle Ltd.