Home > Software design >  How to get only "p" tags inside "small single" article?
How to get only "p" tags inside "small single" article?

Time:03-25

I need to get all p tags (text inside them) inside article.

Into this (after Try {...} is free to edit):

var d2 = ""; Try { d2 = *(driver.findElements(By.tagName("p"))).head.getText }

CodePudding user response:

You can use either of the following locator strategies:

  • Using xpath:

    var d2 = ""; 
    Try { d2 = *(driver.findElements(By.xpath("//article[@class='small single']//p"))).head.getText }
    
  • Using cssSelector:

    var d2 = ""; 
    Try { d2 = *(driver.findElements(By.cssSelector("article.small.single p"))).head.getText }
    

CodePudding user response:

Try to avoid mutability wherever possible in Scala. Using the selector from undetected Selenium's answer:

import scala.collection.JavaConverters

val javaData = driver.findElements(By.cssSelector("article.small.single p"))

val data: Seq[String] = JavaConverters.asScalaBufferConverter(javaData)
  .asScala
  .map(element => element.getText)

driver.findElements returns a Java List, so we need to convert it into a Scala collection before being able to use .map over it.

  • Related