Search code examples
scalajsoup

Scala scraper select a tag with attribute presents


How to select a tag with some attribute present, e.g. a tag with href attribute <a href="..."> using Scala scraper using a single query instead of multiple unsafe queries like following?

val browser = JsoupBrowser()
val doc = browser.get("https://...")
val a = doc >> element("a")
val h = a >> attr("href")

Solution

  • As described for example here, you can use a tag selector a combined with an attribute selector [href]:

    doc.select("a[href]")
    

    In general, you can also further constrain the values of the attribute with the [name=value] syntax. If you only want to check the existence of the attribute, [name] should be enough.