SwiftSoup is a pure Swift library that allows for parsing, manipulating, and outputting HTML on iOS and macOS. To select elements using CSS selectors in SwiftSoup, you need to first parse the HTML content into a Document
object. Then you can use the select(_:)
method on this object, passing in the CSS selector string to retrieve the elements you're interested in.
Here's a step-by-step guide on how to do this:
Add SwiftSoup to your project. You can do this via CocoaPods, Carthage, or Swift Package Manager.
Import the SwiftSoup library in your Swift file:
import SwiftSoup
- Parse the HTML content into a
Document
. This can be HTML content from a string, a local HTML file, or content fetched from the web:
let html = "<html><head><title>First parse</title></head>"
+ "<body><p>Parsed HTML into a doc.</p></body></html>"
do {
let doc: Document = try SwiftSoup.parse(html)
// Now you can use the doc object to select elements
} catch Exception.Error(let type, let message) {
print(message)
} catch {
print("error")
}
- Use the
select(_:)
method to find elements with a specific CSS selector:
do {
// Assuming `doc` is the Document you have parsed
let elements = try doc.select("p")
for element in elements {
print(try element.text())
}
} catch Exception.Error(let type, let message) {
print(message)
} catch {
print("error")
}
In the example above, all <p>
elements in the HTML are selected and their text content is printed.
Here are some examples of CSS selectors you might use:
"p"
: Selects all<p>
elements.".class-name"
: Selects all elements withclass="class-name"
."#id"
: Selects the element withid="id"
."div > p"
: Selects all<p>
elements where the parent is a<div>
element."a[href]"
: Selects all<a>
elements with anhref
attribute.
Remember that SwiftSoup follows the same CSS selector syntax that you would use in JavaScript with libraries like jQuery or in CSS stylesheets.
Here's a more comprehensive example that selects elements based on their class:
let html = """
<html>
<body>
<div class="container">
<p class="item">Item 1</p>
<p class="item">Item 2</p>
<p class="other-item">Item 3</p>
</div>
</body>
</html>
"""
do {
let doc: Document = try SwiftSoup.parse(html)
let items = try doc.select(".item")
for item in items {
print(try item.text()) // Outputs: Item 1 Item 2
}
} catch Exception.Error(let type, let message) {
print(message)
} catch {
print("error")
}
This code snippet will select and print the text of all elements with the class item
.