1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
//! Inspired by the Python library "BeautifulSoup," `soup` is a layer on top of
//! `html5ever` that aims to provide a slightly different API for querying &
//! manipulating HTML
//!
//! # Examples (inspired by bs4's docs)
//!
//! Here is the HTML document we will be using for the rest of the examples:
//!
//! ```
//! const THREE_SISTERS: &'static str = r#"
//! <html><head><title>The Dormouse's story</title></head>
//! <body>
//! <p class="title"><b>The Dormouse's story</b></p>
//!
//! <p class="story">Once upon a time there were three little sisters; and their names were
//! <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
//! <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
//! <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
//! and they lived at the bottom of a well.</p>
//!
//! <p class="story">...</p>
//! "#;
//! # fn main() {}
//! ```
//!
//! First let's try searching for a tag with a specific name:
//!
//! ```
//! # extern crate soup;
//! # const THREE_SISTERS: &'static str = r#"
//! # <html><head><title>The Dormouse's story</title></head>
//! # <body>
//! # <p class="title"><b>The Dormouse's story</b></p>
//! #
//! # <p class="story">Once upon a time there were three little sisters; and their names were
//! # <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
//! # <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
//! # <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
//! # and they lived at the bottom of a well.</p>
//! #
//! # <p class="story">...</p>
//! # "#;
//! # fn main() {
//! use soup::prelude::*;
//!
//! let soup = Soup::new(THREE_SISTERS);
//!
//! let title = soup.tag("title").find().expect("Couldn't find tag 'title'");
//! assert_eq!(title.display(), "<title>The Dormouse's story</title>");
//! assert_eq!(title.name(), "title");
//! assert_eq!(title.text(), "The Dormouse's story".to_string());
//! assert_eq!(title.parent().expect("Couldn't find parent of 'title'").name(), "head");
//!
//! let p = soup.tag("p").find().expect("Couldn't find tag 'p'");
//! assert_eq!(
//!     p.display(),
//!     r#"<p class="title"><b>The Dormouse's story</b></p>"#
//! );
//! assert_eq!(p.get("class"), Some("title".to_string()));
//! # }
//! ```
//!
//! So we see that `.find` will give us the first element that matches the query, and we've seen some
//! of the methods that we can call on the results. But what if we want to retrieve more than one
//! element with the query? For that, we'll use `.find_all`:
//!
//! ```
//! # extern crate soup;
//! # use soup::prelude::*;
//! # const THREE_SISTERS: &'static str = r#"
//! # <html><head><title>The Dormouse's story</title></head>
//! # <body>
//! # <p class="title"><b>The Dormouse's story</b></p>
//! #
//! # <p class="story">Once upon a time there were three little sisters; and their names were
//! # <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
//! # <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
//! # <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
//! # and they lived at the bottom of a well.</p>
//! #
//! # <p class="story">...</p>
//! # "#;
//! # fn main() {
//! # let soup = Soup::new(THREE_SISTERS);
//! // .find returns only the first 'a' tag
//! let a = soup.tag("a").find().expect("Couldn't find tag 'a'");
//! assert_eq!(
//!     a.display(),
//!     r#"<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>"#
//! );
//! // but .find_all will return _all_ of them:
//! let a_s = soup.tag("a").find_all();
//! assert_eq!(
//!     a_s.map(|a| a.display())
//!        .collect::<Vec<_>>()
//!        .join("\n"),
//!     r#"<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>
//! <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>
//! <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>"#
//! );
//! # }
//! ```
//!
//! Since `.find_all` returns an iterator, you can use it with all the methods you would
//! use with other iterators:
//!
//! ```
//! # extern crate soup;
//! # use soup::prelude::*;
//! # const THREE_SISTERS: &'static str = r#"
//! # <html><head><title>The Dormouse's story</title></head>
//! # <body>
//! # <p class="title"><b>The Dormouse's story</b></p>
//! #
//! # <p class="story">Once upon a time there were three little sisters; and their names were
//! # <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
//! # <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
//! # <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
//! # and they lived at the bottom of a well.</p>
//! #
//! # <p class="story">...</p>
//! # "#;
//! # fn main() {
//! # let soup = Soup::new(THREE_SISTERS);
//! let expected = [
//!     "http://example.com/elsie",
//!     "http://example.com/lacie",
//!     "http://example.com/tillie",
//! ];
//!
//! for (i, link) in soup.tag("a").find_all().enumerate() {
//!     let href = link.get("href").expect("Couldn't find link with 'href' attribute");
//!     assert_eq!(href, expected[i].to_string());
//! }
//! # }
//! ```
//!
//! The top-level structure we've been working with here, `soup`, implements the same methods
//! that the query results do, so you can call the same methods on it and it will delegate the
//! calls to the root node:
//!
//! ```
//! # extern crate soup;
//! # use soup::prelude::*;
//! # const THREE_SISTERS: &'static str = r#"
//! # <html><head><title>The Dormouse's story</title></head>
//! # <body>
//! # <p class="title"><b>The Dormouse's story</b></p>
//! #
//! # <p class="story">Once upon a time there were three little sisters; and their names were
//! # <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
//! # <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
//! # <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
//! # and they lived at the bottom of a well.</p>
//! #
//! # <p class="story">...</p>
//! # "#;
//! # fn main() {
//! # let soup = Soup::new(THREE_SISTERS);
//! let text = soup.text();
//! assert_eq!(
//!     text,
//!     r#"The Dormouse's story
//!
//! The Dormouse's story
//!
//! Once upon a time there were three little sisters; and their names were
//! Elsie,
//! Lacie and
//! Tillie;
//! and they lived at the bottom of a well.
//!
//! ...
//! "#
//! );
//! # }
//! ```
//!
//! You can use more than just strings to search for results, such as Regex:
//!
//! ```rust
//! # extern crate regex;
//! # extern crate soup;
//! # use soup::prelude::*;
//! # use std::error::Error;
//! use regex::Regex;
//! # fn main() -> Result<(), Box<Error>> {
//!
//! let soup = Soup::new(r#"<body><p>some text, <b>Some bold text</b></p></body>"#);
//! let results = soup.tag(Regex::new("^b")?)
//!                   .find_all()
//!                   .map(|tag| tag.name().to_string())
//!                   .collect::<Vec<_>>();
//! assert_eq!(results, vec!["body".to_string(), "b".to_string()]);
//! #   Ok(())
//! # }
//! ```
//!
//! Passing `true` will match everything:
//!
//! ```rust
//! # extern crate soup;
//! # use soup::prelude::*;
//! # use std::error::Error;
//! # fn main() -> Result<(), Box<Error>> {
//!
//! let soup = Soup::new(r#"<body><p>some text, <b>Some bold text</b></p></body>"#);
//! let results = soup.tag(true)
//!                   .find_all()
//!                   .map(|tag| tag.name().to_string())
//!                   .collect::<Vec<_>>();
//! assert_eq!(results, vec![
//!     "html".to_string(),
//!     "head".to_string(),
//!     "body".to_string(),
//!     "p".to_string(),
//!     "b".to_string(),
//! ]);
//! #   Ok(())
//! # }
//! ```
//!
//! (also, passing `false` will always return no results, though if that is useful to you, please let me know)
//!
//! So what can you do once you get the result of a query? Well, for one thing, you can traverse the tree a few
//! different ways. You can ascend the tree:
//!
//! ```rust
//! # extern crate soup;
//! # use soup::prelude::*;
//! # use std::error::Error;
//! # fn main() -> Result<(), Box<Error>> {
//!
//! let soup = Soup::new(r#"<body><p>some text, <b>Some bold text</b></p></body>"#);
//! let b = soup.tag("b")
//!             .find()
//!             .expect("Couldn't find tag 'b'");
//! let p = b.parent()
//!          .expect("Couldn't find parent of 'b'");
//! assert_eq!(p.name(), "p".to_string());
//! let body = p.parent()
//!             .expect("Couldn't find parent of 'p'");
//! assert_eq!(body.name(), "body".to_string());
//! #   Ok(())
//! # }
//! ```
//!
//! Or you can descend it:
//!
//! ```rust
//! # extern crate soup;
//! # use soup::prelude::*;
//! # use std::error::Error;
//! # fn main() -> Result<(), Box<Error>> {
//!
//! let soup = Soup::new(r#"<body><ul><li>ONE</li><li>TWO</li><li>THREE</li></ul></body>"#);
//! let ul = soup.tag("ul")
//!             .find()
//!             .expect("Couldn't find tag 'ul'");
//! let mut li_tags = ul.children().filter(|child| child.is_element());
//! assert_eq!(li_tags.next().map(|tag| tag.text().to_string()), Some("ONE".to_string()));
//! assert_eq!(li_tags.next().map(|tag| tag.text().to_string()), Some("TWO".to_string()));
//! assert_eq!(li_tags.next().map(|tag| tag.text().to_string()), Some("THREE".to_string()));
//! assert!(li_tags.next().is_none());
//! #   Ok(())
//! # }
//! ```
//!
//! Or ascend it with an iterator:
//!
//! ```rust
//! # extern crate soup;
//! # use soup::prelude::*;
//! # use std::error::Error;
//! # fn main() -> Result<(), Box<Error>> {
//!
//! let soup = Soup::new(r#"<body><ul><li>ONE</li><li>TWO</li><li>THREE</li></ul></body>"#);
//! let li = soup.tag("li").find().expect("Couldn't find tag 'li'");
//! let mut parents = li.parents();
//! assert_eq!(parents.next().map(|tag| tag.name().to_string()), Some("ul".to_string()));
//! assert_eq!(parents.next().map(|tag| tag.name().to_string()), Some("body".to_string()));
//! assert_eq!(parents.next().map(|tag| tag.name().to_string()), Some("html".to_string()));
//! assert_eq!(parents.next().map(|tag| tag.name().to_string()), Some("[document]".to_string()));
//! #   Ok(())
//! # }
//! ```
#![deny(
    missing_docs,
    missing_debug_implementations,
    missing_copy_implementations,
    trivial_casts,
    trivial_numeric_casts,
    unsafe_code,
    unstable_features,
    unused_import_braces,
    unused_qualifications,
    rust_2018_compatibility,
    rust_2018_idioms
)]
extern crate html5ever;
#[cfg(feature = "regex")]
extern crate regex;

use html5ever::{
    parse_document,
    rcdom::RcDom,
    tendril::TendrilSink,
};
use std::{
    fmt,
    io::{self, Read},
};

/// This module exports all the important types & traits to use `soup`
/// effectively
pub mod prelude {
    pub use crate::{node_ext::NodeExt, qb_ext::QueryBuilderExt, Soup};
}

pub use crate::{find::QueryBuilder, node_ext::NodeExt, qb_ext::QueryBuilderExt};

mod attribute;
mod find;
mod qb_ext;
mod node_ext;
pub mod pattern;

/// Parses HTML & provides methods to query & manipulate the document
pub struct Soup {
    handle: RcDom,
}

impl Soup {
    /// Create a new `Soup` instance from a string slice
    ///
    /// # Example
    ///
    /// ```rust
    /// # extern crate soup;
    /// # use soup::prelude::*;
    /// # use std::error::Error;
    /// # fn main() -> Result<(), Box<Error>> {
    /// let html = r#"
    /// <!doctype html>
    /// <html>
    ///   <head>
    ///     <title>page title</title>
    ///   </head>
    ///   <body>
    ///     <h1>Heading</h1>
    ///     <p>Some text</p>
    ///     <p>Some more text</p>
    ///   </body>
    /// </html>
    /// "#;
    ///
    /// let soup = Soup::new(html);
    /// #   Ok(())
    /// # }
    /// ```
    pub fn new(html: &str) -> Soup {
        let dom = parse_document(RcDom::default(), Default::default())
            .from_utf8()
            .one(html.as_bytes());
        Soup {
            handle: dom,
        }
    }

    /// Create a new `Soup` instance from something that implements `Read`
    ///
    /// This is good for parsing the output of an HTTP response, for example.
    ///
    /// ```rust,no_run
    /// # extern crate reqwest;
    /// # extern crate soup;
    /// # use std::error::Error;
    /// use soup::prelude::*;
    ///
    /// # fn main() -> Result<(), Box<Error>> {
    /// let response = reqwest::get("https://docs.rs/soup")?;
    /// let soup = Soup::from_reader(response)?;
    /// #   Ok(())
    /// # }
    /// ```
    pub fn from_reader<R: Read>(mut reader: R) -> io::Result<Soup> {
        let dom = parse_document(RcDom::default(), Default::default())
            .from_utf8()
            .read_from(&mut reader)?;
        Ok(Soup {
            handle: dom,
        })
    }

    /// Extracts all text from the HTML
    pub fn text(&self) -> String {
        self.handle.document.text()
    }
}

impl From<RcDom> for Soup {
    fn from(rc: RcDom) -> Soup {
        Soup {
            handle: rc
        }
    }
}

impl fmt::Debug for Soup {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.handle.document.text())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    const TEST_HTML_STRING: &'static str = r#"
<!doctype html>
<html>
  <head>
    <title>foo</title>
  </head>
  <body>
    <p>One</p>
    <p>Two</p>
  </body>
</html>
"#;

    #[test]
    fn find() {
        let soup = Soup::new(TEST_HTML_STRING);
        let result = soup.tag("p").find().expect("Couldn't find tag 'p'");
        assert_eq!(result.text(), "One".to_string());
    }

    #[test]
    fn find_all() {
        let soup = Soup::new(TEST_HTML_STRING);
        let result = soup
            .tag("p")
            .find_all()
            .map(|p| p.text())
            .collect::<Vec<_>>();
        assert_eq!(result, vec!["One".to_string(), "Two".to_string()]);
    }
}