score:16
This may help you Processing real world HTML as if it were XML in scala
score:2
/*
Copyright (c) 2008 Florian Hars, BIK Aschpurwis+Behrens GmbH, Hamburg
Copyright (c) 2002-2008 EPFL, Lausanne, unless otherwise specified.
All rights reserved.
This software was developed by the Programming Methods Laboratory of the
Swiss Federal Institute of Technology (EPFL), Lausanne, Switzerland.
Permission to use, copy, modify, and distribute this software in source
or binary form for any purpose with or without fee is hereby granted,
provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the EPFL nor the names of its contributors
may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
*/
package tagsoup
import org.xml.sax.InputSource
import javax.xml.parsers.SAXParser
import org.ccil.cowan.tagsoup.jaxp.SAXFactoryImpl
import scala.xml.parsing.FactoryAdapter
import scala.xml._
class TagSoupFactoryAdapter extends FactoryAdapter {
val parserFactory = new SAXFactoryImpl
parserFactory.setNamespaceAware(false)
val emptyElements = Set("area", "base", "br", "col", "hr", "img",
"input", "link", "meta", "param")
/** Tests if an XML element contains text.
* @return true if element named <code>localName</code> contains text.
*/
def nodeContainsText(localName: String) = !(emptyElements contains localName)
/** creates a node.
*/
def createNode(pre:String, label: String, attrs: MetaData,
scpe: NamespaceBinding, children: List[Node] ): Elem = {
Elem( pre, label, attrs, scpe, children:_* );
}
/** creates a text node
*/
def createText( text:String ) =
Text( text );
/** Ignore Processing Instructions
*/
def createProcInstr(target: String, data: String) = Nil
/** load XML document
* @param source
* @return a new XML document object
*/
override def loadXML(source: InputSource) = {
val parser: SAXParser = parserFactory.newSAXParser()
scopeStack.push(TopScope)
parser.parse(source, this)
scopeStack.pop
rootElem
}
}
score:5
Try using scala.xml.parsing.XhtmlParser
instead.
score:5
I have just tried to use this answer with scala 2.8.1 and ended up using the work from:
http://www.hars.de/2009/01/html-as-xml-in-scala.html
The interesting bit that I needed was:
val parserFactory = new org.ccil.cowan.tagsoup.jaxp.SAXFactoryImpl
val parser = parserFactory.newSAXParser()
val source = new org.xml.sax.InputSource("http://www.scala-lang.org")
val adapter = new scala.xml.parsing.NoBindingFactoryAdapter
adapter.loadXML(source, parser)
score:5
Scala Scraper
I recommend Scala Scraper that lets you parse HTML elegantly like this:
// Parse elements from files, URLs or plain strings
val browser = JsoupBrowser()
val doc = browser.parseFile("core/src/test/resources/example.html")
val doc2 = browser.get("http://example.com")
val doc3 = browser.parseString("<html><h1>parse me</h1></html>")
// Extract the text inside the element with id "header"
doc >> text("#header")
// Extract the <span> elements inside #menu
val items = doc >> elementList("#menu span")
// From each item, extract all the text inside their <a> elements
items.map(_ >> allText("a"))
Examples are taken from the Scala Scraper's readme.
Source: stackoverflow.com
Related Query
- Scala and HTML parsing
- Parsing JSON in Play2 and Scala without Data Type
- Scala / Lift - Trying to understand Lift's simultaneous claim to use valid html and propensity for lift: tags and tag rewriting in render
- Grammars, Scala Parsing Combinators and Orderless Sets
- Parsing and manipulating json in Scala
- Parsing JSON and iterating through the object in Scala
- Unable to choose a correct combinator for parsing and deal with it in Scala
- Play Framework and Scala Json, parsing for json containing JSArray and JSObject
- Parsing command line args and executing a function in scala
- Scala XML validation by XSD and parsing
- Thymeleaf with springboot and Scala not rendering HTML page
- How to use scala and html code inside single block
- Is there a way to convert Scala-Spark DataFrame to HTML table, or converting DataFrame to Scala map then convert to Json and then HTML?
- Scala IDE 3.0.4 editor support for html and sbt
- Dynamic HTML ID with Bootstrap, Play framework and Scala templates
- Parsing large JSON file with Scala and JSON4S
- Parsing HTML table using Jsoup Scala
- How might I use HTML 5 for Scala input and output?
- How to manage html inside application which uses spray and scala
- Scala XML parsing with real-world HTML (with unmatched tag)
- Loading and Parsing JSON with Spark using Scala Jackson library
- Format a string and replace %s with html element in scala play framework
- Parsing special characters (e.g., è, é, and ®) JSONs in Play for Scala (version 2.3.x)
- How do you read the HTML content of an Atom feed with Scala and Play framework 2.0?
- Parsing text and representing it with tokens using Scala
- Difference between object and class in Scala
- What is the formal difference in Scala between braces and parentheses, and when should they be used?
- Difference between a Seq and a List in Scala
- What are Scala context and view bounds?
- Difference between method and function in Scala
More Query from same tag
- Scala & Play: route regex without identifier
- Euclidean distance in spark 2.1
- How to use scala type alias (Int, String)
- How to implement Actor based HTTP Routing in Akka
- Type conversion from Any object: pattern matching vs Try()
- Scala, String representation of a function
- Can I use shapeless to return the same arity of HList as passed HList?
- Scala 2D Animation library
- How to access test resources in Scala?
- SQL interpolation with ScalikeJDBC
- Iterate over elements of columns Scala
- Scala Catalog of functional Design Patterns
- Scala function call with unknown default parameter
- leaflet map does not appear correctly until resize
- Library 'scala-2.10.0-RC1 not used' thrown by IntelliJ integrating a Play 2 app
- How strongly is scala tied to JVM?
- Decode incomplete ADT with Circe
- Why are so many new languages written for the Java VM?
- Finding pairs of sets so that their union has a specific size
- Iterate a spark dataframe efficiently without using collect
- Why this code compiles and it gives runtime error when it executes
- i want to store each rdd into database in twitter streaming using apache spark but got error of task not serialize in scala
- Spark sql using spark thrift server
- Combine output of parallel operations using Scala
- Input Spark Dataframe to DeepLearning4J model
- scala spark use expr to value inside a column
- How to constraint a type variable with multiple constraints?
- Selection Sort Generic type implementation
- Scala unit test to check for constant value
- How to read a text file with mixed encodings in Scala or Java?