Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Convert <br> to '\n' in text? #178

Closed
failable opened this issue Mar 30, 2024 · 1 comment
Closed

Convert <br> to '\n' in text? #178

failable opened this issue Mar 30, 2024 · 1 comment

Comments

@failable
Copy link

failable commented Mar 30, 2024

The following code snippet outputs "Hello, world!good bye".

    use scraper::{Html, Selector};

    let fragment = Html::parse_fragment("<div>Hello, world!<br><p>good bye</p></div>");
    let selector = Selector::parse("div").unwrap();

    let div = fragment.select(&selector).next().unwrap();

    println!("{:#?}", div.text().collect::<String>());

Would it better to output "Hello, world!\ngood bye"?

@adamreichold
Copy link
Contributor

If you want this particular transformation, you will need to replace the <br/> Element node by a \n Text node and then use .text().collect::<String>().

Alternatively, you can use .descendants() instead of .text() and filter for text nodes and <br/> tags directly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants