Go through element list item by find_elements_by_class_name in Selenium Python

0

I'm starting with Selenium I have the following html code

<!DOCTYPE html>
<html lang="es" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <div class="error">
      <h4>Error 1</h4>
      <p>Mi error 1</p>
    </div>
    <div class="error">
      <h4>Error 2</h4>
      <p>Este es el Error 2</p>
    </div>
    <div class="error">
      <h4>Error 3</h4>
      <p>Acceder</p>
    </div>
    <div class="ok">
      <h4>Esto OK</h4>
      <p>Esto esta OK</p>
    </div>
    <div class="error">
      <h4>Error 4</h4>
      <p>Otro error</p>
    </div>
  </body>
</html>

Well, what I want to retrieve is the value of the " p " tag with the text value "Sign in"

for this in the Selenium Webdriver in Python I have the following code

elementos=driver.find_elements_by_class_name("error") 
for elem in elementos   
    ### aqui quiero selecionar la etiqueta "<p>" de elem

but I'm not sure how I can select it to pick up the text.

Salu2

    
asked by Thenine 22.11.2018 в 12:52
source

2 answers

0

I would try to use searches by xPath or by CSS. Here is an example of xpath:

driver.find_element_by_xpath(".//p[text()='Acceder']")

With this you do not need any loop.

    
answered by 22.11.2018 в 13:02
0

Using any of the methods selenium gives you to locate an element (by name, by class, by id, by selector css, by xpath, ...) the result you get is a webelement . This object has the same methods as the driver , so you can search inside again by name, class, id, etc ...

For example, the following loop would take you the texts of the <p> tags that are inside another element with class "error" , which is more or less what you were trying to do in the code that you have put in the question :

elementos=driver.find_elements_by_class_name("error") 
for elem in elemento:
    p = elem.find_element_by_tag_name("p")
    print(p[0].text)

But you can save yourself from repeating searches if the items you select are directly the <p> , instead of the <div> . For this you need to express that you want "p elements that are children of a div element of the class" error. "This can be expressed by Xpath, or by CSS expressions, depending on what you are more used to, for example:

# Usando selector css
elementos = driver.find_element_by_css_selector("div.error p")

# Usando xpath
elementos = driver.find_element_by_xpath("//div[@class='error']/p")

In either of the two ways you get the list with the <p> that you were interested in and you can iterate through it:

for p in elementos:
    print(p.text)

Now, if you do not need all the p , but only those containing the text 'Access' a more elaborate Xpath expression that would return only those would be:

elementos = driver.find_element_by_xpath("//div[@class='error']/p[text()='Acceder']")
    
answered by 22.11.2018 в 13:12