1
1
---
2
- title : " Finding web elements "
2
+ title : " Encontrando Elementos Web "
3
3
linkTitle : " Finders"
4
4
weight : 2
5
5
needsTranslation : true
@@ -8,39 +8,37 @@ aliases: [
8
8
" /pt-br/documentation/webdriver/locating_elements/"
9
9
]
10
10
description : >
11
- Locating the elements based on the provided locator values .
11
+ Localizando elementos com base nos valores providenciados pelo localizador .
12
12
---
13
-
14
- One of the most fundamental aspects of using Selenium is obtaining element references to work with.
15
- Selenium offers a number of built-in [ locator strategies] ({{< ref "locators.md" >}}) to uniquely identify an element.
16
- There are many ways to use the locators in very advanced scenarios. For the purposes of this documentation,
17
- let's consider this HTML snippet:
13
+ Um dos aspectos mais fundamentais do uso do Selenium é obter referências de elementos para trabalhar.
14
+ O Selenium oferece várias [ estratégias de localizador] ({{< ref "locators.md" >}}) para identificar exclusivamente um elemento.
15
+ Há muitas maneiras de usar os localizadores em cenários complexos. Para os propósitos desta documentação,
16
+ vamos considerar este trecho de HTML:
18
17
19
18
20
19
``` html
21
20
<ol id =" vegetables" >
22
21
<li class =" potatoes" >…
23
22
<li class =" onions" >…
24
- <li class =" tomatoes" ><span >Tomato is a Vegetable </span >…
23
+ <li class =" tomatoes" ><span >O tomate é um vegetal </span >…
25
24
</ol >
26
25
<ul id =" fruits" >
27
26
<li class =" bananas" >…
28
27
<li class =" apples" >…
29
- <li class =" tomatoes" ><span >Tomato is a Fruit </span >…
28
+ <li class =" tomatoes" ><span >O tomate é uma fruta </span >…
30
29
</ul >
31
30
```
32
31
33
- ## First matching element
34
-
35
- Many locators will match multiple elements on the page. The singular find element method will return a reference to the
36
- first element found within a given context.
37
-
38
- ### Evaluating entire DOM
32
+ ## Primeiro Elemento correspondente
33
+ Muitos localizadores irão corresponder a vários elementos na página.
34
+ O método de elemento de localização singular retornará uma referência ao
35
+ primeiro elemento encontrado dentro de um determinado contexto.
39
36
40
- When the find element method is called on the driver instance, it
41
- returns a reference to the first element in the DOM that matches with the provided locator.
42
- This value can be stored and used for future element actions. In our example HTML above, there are
43
- two elements that have a class name of "tomatoes" so this method will return the element in the "vegetables" list.
37
+ ### Avaliando o DOM inteiro
38
+ Quando o metodo find element é chamado na instância do driver, ele
39
+ retorna uma referência ao primeiro elemento no DOM que corresponde ao localizador fornecido.
40
+ Esse valor pode ser guardado e usado para ações futuras do elemento. Em nosso exemplo HTML acima, existem
41
+ dois elementos que têm um nome de classe de "tomatoes" então este método retornará o elemento na lista "vegetables".
44
42
45
43
{{< tabpane langEqualsHeader=true >}}
46
44
{{< tab header="Java" >}}
@@ -64,14 +62,13 @@ val vegetable: WebElement = driver.findElement(By.className("tomatoes"))
64
62
{{< /tabpane >}}
65
63
66
64
67
- ### Evaluating a subset of the DOM
65
+ ### Avaliando um subconjunto do DOM
66
+ Ao em vez de tentar encontrar um localizador unico no DOM inteiro, normalmente é útil restringir a busca ao escopo de outro elemento
67
+ já localizado. No exemplo acima existem dois elementos com um nome de classe de "tomatoes" e
68
+ é um pouco mais desafiador obter a referência para o segundo.
68
69
69
- Rather than finding a unique locator in the entire DOM, it is often useful to narrow the search to the scope
70
- of another located element. In the above example there are two elements with a class name of "tomatoes" and
71
- it is a little more challenging to get the reference for the second one.
72
-
73
- One solution is to locate an element with a unique attribute that is an ancestor of the desired element and not an
74
- ancestor of the undesired element, then call find element on that object:
70
+ Uma possível solução seria localizar um elemento com um atributo único que seja um ancestral do elemento desejado e não um
71
+ ancestral do elemento indesejado, então invoque o find element nesse objeto:
75
72
76
73
{{< tabpane langEqualsHeader=true >}}
77
74
{{< tab header="Java" >}}
@@ -101,23 +98,22 @@ val fruit = fruits.findElement(By.id("tomatoes"))
101
98
{{< /tabpane >}}
102
99
103
100
{{% pageinfo color="info" %}}
104
- ** Java and C#** <br >
105
- ` WebDriver ` , ` WebElement ` and ` ShadowRoot ` classes all implement a ` SearchContext ` interface, which is
106
- considered a _ role-based interface_ . Role-based interfaces allow you to determine whether a particular
107
- driver implementation supports a given feature. These interfaces are clearly defined and try
108
- to adhere to having only a single role of responsibility .
101
+ ** Java e C#** <br >
102
+ As classes ` WebDriver ` , ` WebElement ` e ` ShadowRoot ` todas implementam o ` SearchContext ` interface, que é
103
+ considerada uma _ role-based interface_ (interface baseada em função). As interfaces baseadas em função permitem determinar se uma determinada
104
+ implementação de driver suporta um recurso específico. Essas interfaces são claramente definidas e tentam
105
+ aderir a ter apenas um único papel de responsabilidade .
109
106
{{% /pageinfo %}}
110
107
111
- ### Optimized locator
112
-
113
- A nested lookup might not be the most effective location strategy since it requires two
114
- separate commands to be issued to the browser.
108
+ ### Localizador otimizado
109
+ Uma pesquisa aninhada pode não ser a estratégia de localização mais eficaz, pois requer dois
110
+ comandos separados a serem emitidos para o navegador.
115
111
116
- To improve the performance slightly, we can use either CSS or XPath to find this element in a single command .
117
- See the [ Locator strategy suggestions ] ({{< ref "/documentation/test_practices/encouraged/locators" >}}) in our
118
- [ Encouraged test practices ] ({{< ref "/documentation/test_practices/encouraged" >}}) section .
112
+ Para melhorar um pouco o desempenho, podemos usar CSS ou XPath para encontrar esse elemento com um único comando .
113
+ Veja as [ sugestões de estratégia do localizador ] ({{< ref "/documentation/test_practices/encouraged/locators" >}}) na nossa sessão de
114
+ [ Práticas de teste incentivadas ] ({{< ref "/documentation/test_practices/encouraged" >}}).
119
115
120
- For this example, we'll use a CSS Selector:
116
+ Para esse exemplo, utilizaremos o CSS Selector:
121
117
122
118
{{< tabpane langEqualsHeader=true >}}
123
119
{{< tab header="Java" >}}
@@ -141,12 +137,11 @@ val fruit = driver.findElement(By.cssSelector("#fruits .tomatoes"))
141
137
{{< /tabpane >}}
142
138
143
139
144
- ## All matching elements
145
-
146
- There are several use cases for needing to get references to all elements that match a locator, rather
147
- than just the first one. The plural find elements methods return a collection of element references.
148
- If there are no matches, an empty list is returned. In this case,
149
- references to all fruits and vegetable list items will be returned in a collection.
140
+ ## Todos os elementos correspondentes
141
+ Existem vários casos de uso para a necessidade de obter referências a todos os elementos que correspondem a um localizador, em vez
142
+ do que apenas o primeiro. Os métodos plurais find elements retornam uma coleção de referências de elementos.
143
+ Se não houver correspondências, uma lista vazia será retornada. Nesse caso,
144
+ referências a todos os itens da lista de frutas e vegetais serão devolvidas em uma coleção.
150
145
151
146
{{< tabpane langEqualsHeader=true >}}
152
147
{{< tab header="Java" >}}
@@ -169,9 +164,9 @@ val plants: List<WebElement> = driver.findElements(By.tagName("li"))
169
164
{{< /tab >}}
170
165
{{< /tabpane >}}
171
166
172
- ### Get element
173
- Often you get a collection of elements but want to work with a specific element, which means you
174
- need to iterate over the collection and identify the one you want .
167
+ ### Obter Elemento
168
+ Muitas vezes você obterá uma coleção de elementos, mas quer trabalhar apenas com um elemento específico, o que significa que você
169
+ precisa iterar sobre a coleção e identificar o que você deseja .
175
170
176
171
177
172
{{< tabpane langEqualsHeader=true >}}
@@ -188,10 +183,10 @@ from selenium.webdriver.common.by import By
188
183
189
184
driver = webdriver.Firefox()
190
185
191
- # Navigate to Url
186
+ # Navegar até a URL
192
187
driver.get("https://www.example.com ")
193
188
194
- # Get all the elements available with tag name 'p'
189
+ # Obtém todos os elementos disponiveis com o nome da tag 'p'
195
190
elements = driver.find_elements(By.TAG_NAME, 'p')
196
191
197
192
for e in elements:
@@ -207,10 +202,10 @@ namespace FindElementsExample {
207
202
public static void Main(string[ ] args) {
208
203
IWebDriver driver = new FirefoxDriver();
209
204
try {
210
- // Navigate to Url
205
+ // Navegar até a URL
211
206
driver.Navigate().GoToUrl("https://example.com ");
212
207
213
- // Get all the elements available with tag name 'p'
208
+ // Obtém todos os elementos disponiveis com o nome da tag 'p'
214
209
IList < IWebElement > elements = driver.FindElements(By.TagName("p"));
215
210
foreach(IWebElement e in elements) {
216
211
System.Console.WriteLine(e.Text);
@@ -227,10 +222,10 @@ namespace FindElementsExample {
227
222
require 'selenium-webdriver'
228
223
driver = Selenium::WebDriver.for : firefox
229
224
begin
230
- # Navigate to URL
225
+ # Navegar até a URL
231
226
driver.get 'https://www.example.com '
232
227
233
- # Get all the elements available with tag name 'p'
228
+ # Obtém todos os elementos disponiveis com o nome da tag 'p'
234
229
elements = driver.find_elements(: tag_name ,'p')
235
230
236
231
elements.each { |e|
@@ -245,10 +240,10 @@ const {Builder, By} = require('selenium-webdriver');
245
240
(async function example() {
246
241
let driver = await new Builder().forBrowser('firefox').build();
247
242
try {
248
- // Navigate to Url
243
+ // Navegar até a URL
249
244
await driver.get('https://www.example.com ');
250
245
251
- // Get all the elements available with tag 'p'
246
+ // Obtém todos os elementos disponiveis com o nome da tag 'p'
252
247
let elements = await driver.findElements(By.css('p'));
253
248
for(let e of elements) {
254
249
console.log(await e.getText());
@@ -267,7 +262,7 @@ fun main() {
267
262
val driver = FirefoxDriver()
268
263
try {
269
264
driver.get("https://example.com ")
270
- // Get all the elements available with tag name 'p'
265
+ // Obtém todos os elementos disponiveis com o nome da tag 'p'
271
266
val elements = driver.findElements(By.tagName("p"))
272
267
for (element in elements) {
273
268
println("Paragraph text:" + element.text)
@@ -279,10 +274,10 @@ fun main() {
279
274
{{< /tab >}}
280
275
{{< /tabpane >}}
281
276
282
- ## Find Elements From Element
277
+ ## Localizar Elementos em um Elemento
283
278
284
- It is used to find the list of matching child WebElements within the context of parent element .
285
- To achieve this, the parent WebElement is chained with 'findElements' to access child elements
279
+ Ele é usado para localizar a lista de WebElements filhos correspondentes dentro do contexto do elemento pai .
280
+ Para realizar isso, o WebElement pai é encadeado com o 'findElements' para acessar seus elementos filhos.
286
281
287
282
{{< tabpane langEqualsHeader=true >}}
288
283
{{< tab header="Java" >}}
@@ -298,10 +293,10 @@ To achieve this, the parent WebElement is chained with 'findElements' to access
298
293
try {
299
294
driver.get("https://example.com ");
300
295
301
- // Get element with tag name 'div'
296
+ // Obtém o elemento com o nome da tag 'div'
302
297
WebElement element = driver.findElement(By.tagName("div"));
303
298
304
- // Get all the elements available with tag name 'p'
299
+ // Obtém todos os elementos disponiveis com o nome da tag 'p'
305
300
List<WebElement> elements = element.findElements(By.tagName("p"));
306
301
for (WebElement e : elements) {
307
302
System.out.println(e.getText());
@@ -319,10 +314,10 @@ from selenium.webdriver.common.by import By
319
314
driver = webdriver.Chrome()
320
315
driver.get("https://www.example.com ")
321
316
322
- # Get element with tag name 'div'
317
+ # Obtém o elemento com o nome da tag 'div'
323
318
element = driver.find_element(By.TAG_NAME, 'div')
324
319
325
- # Get all the elements available with tag name 'p'
320
+ # Obtém todos os elementos disponíveis com o nome da tag 'p'
326
321
elements = element.find_elements(By.TAG_NAME, 'p')
327
322
for e in elements:
328
323
print(e.text)
@@ -339,10 +334,10 @@ namespace FindElementsFromElement {
339
334
try {
340
335
driver.Navigate().GoToUrl("https://example.com ");
341
336
342
- // Get element with tag name 'div'
337
+ // Obtém o elemento com o nome da tag 'div'
343
338
IWebElement element = driver.FindElement(By.TagName("div"));
344
339
345
- // Get all the elements available with tag name 'p'
340
+ // Obtém todos os elementos disponíveis com o nome da tag 'p'
346
341
IList < IWebElement > elements = element.FindElements(By.TagName("p"));
347
342
foreach(IWebElement e in elements) {
348
343
System.Console.WriteLine(e.Text);
@@ -358,13 +353,13 @@ namespace FindElementsFromElement {
358
353
require 'selenium-webdriver'
359
354
driver = Selenium::WebDriver.for : chrome
360
355
begin
361
- # Navigate to URL
356
+ # Navegar até a URL
362
357
driver.get 'https://www.example.com '
363
358
364
- # Get element with tag name 'div'
359
+ # Obtém o elemento com o nome da tag 'div'
365
360
element = driver.find_element(:tag_name,'div')
366
361
367
- # Get all the elements available with tag name 'p'
362
+ # Obtém todos os elementos disponíveis com o nome da tag 'p'
368
363
elements = element.find_elements(:tag_name,'p')
369
364
370
365
elements.each { |e|
@@ -384,10 +379,10 @@ namespace FindElementsFromElement {
384
379
385
380
await driver.get('https://www.example.com');
386
381
387
- // Get element with tag name 'div'
382
+ // Obtém o elemento com o nome da tag 'div'
388
383
let element = driver.findElement(By.css("div"));
389
384
390
- // Get all the elements available with tag name 'p'
385
+ // Obtém todos os elementos disponíveis com o nome da tag 'p'
391
386
let elements = await element.findElements(By.css("p"));
392
387
for(let e of elements) {
393
388
console.log(await e.getText());
@@ -403,10 +398,10 @@ namespace FindElementsFromElement {
403
398
try {
404
399
driver.get("https://example.com ")
405
400
406
- // Get element with tag name 'div'
401
+ // Obtém o elemento com o nome da tag 'div'
407
402
val element = driver.findElement(By.tagName("div"))
408
403
409
- // Get all the elements available with tag name 'p'
404
+ // Obtém todos os elementos disponíveis com o nome da tag 'p'
410
405
val elements = element.findElements(By.tagName("p"))
411
406
for (e in elements) {
412
407
println(e.text)
@@ -418,9 +413,9 @@ namespace FindElementsFromElement {
418
413
{{< /tab >}}
419
414
{{< /tabpane >}}
420
415
421
- ## Get Active Element
416
+ ## Obter elemento ativo
422
417
423
- It is used to track (or) find DOM element which has the focus in the current browsing context .
418
+ Ele é usado para rastrear (ou) encontrar um elemento DOM que tem o foco no contexto de navegação atual .
424
419
425
420
{{< tabpane langEqualsHeader=true >}}
426
421
{{< tab header="Java" >}}
@@ -434,7 +429,7 @@ It is used to track (or) find DOM element which has the focus in the current bro
434
429
driver.get("http://www.google.com ");
435
430
driver.findElement(By.cssSelector("[ name='q'] ")).sendKeys("webElement");
436
431
437
- // Get attribute of current active element
432
+ // Obter atributo do elemento atualmente ativo
438
433
String attr = driver.switchTo().activeElement().getAttribute("title");
439
434
System.out.println(attr);
440
435
} finally {
@@ -451,7 +446,7 @@ It is used to track (or) find DOM element which has the focus in the current bro
451
446
driver.get("https://www.google.com ")
452
447
driver.find_element(By.CSS_SELECTOR, '[ name="q"] ').send_keys("webElement")
453
448
454
- # Get attribute of current active element
449
+ # Obter atributo do elemento atualmente ativo
455
450
attr = driver.switch_to.active_element.get_attribute("title")
456
451
print(attr)
457
452
{{< /tab >}}
@@ -464,11 +459,11 @@ It is used to track (or) find DOM element which has the focus in the current bro
464
459
public static void Main(string[] args) {
465
460
IWebDriver driver = new ChromeDriver();
466
461
try {
467
- // Navigate to Url
462
+ // Navegar até a URL
468
463
driver.Navigate().GoToUrl("https://www.google.com");
469
464
driver.FindElement(By.CssSelector("[name='q']")).SendKeys("webElement");
470
465
471
- // Get attribute of current active element
466
+ // Obter atributo do elemento atualmente ativo
472
467
string attr = driver.SwitchTo().ActiveElement().GetAttribute("title");
473
468
System.Console.WriteLine(attr);
474
469
} finally {
@@ -485,7 +480,7 @@ It is used to track (or) find DOM element which has the focus in the current bro
485
480
driver.get 'https://www.google.com '
486
481
driver.find_element(css: '[ name="q"] ').send_keys('webElement')
487
482
488
- # Get attribute of current active element
483
+ # Obter atributo do elemento atualmente ativo
489
484
attr = driver.switch_to.active_element.attribute('title')
490
485
puts attr
491
486
ensure
@@ -500,7 +495,7 @@ It is used to track (or) find DOM element which has the focus in the current bro
500
495
await driver.get('https://www.google.com ');
501
496
await driver.findElement(By.css('[ name="q"] ')).sendKeys("webElement");
502
497
503
- // Get attribute of current active element
498
+ // Obter atributo do elemento atualmente ativo
504
499
let attr = await driver.switchTo().activeElement().getAttribute("title");
505
500
console.log(`${attr}`)
506
501
})();
@@ -515,7 +510,7 @@ It is used to track (or) find DOM element which has the focus in the current bro
515
510
driver.get("https://www.google.com ")
516
511
driver.findElement(By.cssSelector("[ name='q'] ")).sendKeys("webElement")
517
512
518
- // Get attribute of current active element
513
+ // Obter atributo do elemento atualmente ativo
519
514
val attr = driver.switchTo().activeElement().getAttribute("title")
520
515
print(attr)
521
516
} finally {
0 commit comments