What is the Mojo::DOM parse?

Overview

The parse method is used to parse an HTML/XML content. This method is provided by the Mojo::DOM module, which is an HTML/XML DOM parser with CSS selectors.

This is the first step we need to do to interact and perform operations on HTML/XML content.

Syntax

$dom->parse('HTML/XML content')

Parameters

The method accepts HTML/XML content as a parameter.

Return value

This method returns the Mojo::DOM object for the given HTML/XML content.

Example

The given HTML is as follows:

<p>Inside paragraph</p>

The output is displayed as follows for the given HTML content:

<p>Inside paragraph</p>

It may look the same, but the parse returned is a Mojo::DOM object, on which we can perform operations.

Code example

use 5.010;
use Mojo::DOM;
# Parse the html
my $dom = Mojo::DOM->new->parse('<p>Inside paragraph</p>');
# Display Mojo::DOM object
say $dom;
# Display text inside the Mojo::DOM object
say $dom->all_text;

Explanation

  • Line 2: We import the Mojo::DOM module.
  • Line 5: We use the parse method to parse the HTML and store it in scalar $dom.
  • Line 8: We display the Mojo::DOM object.
  • Line 11: We use the all_text method to perform an operation to get the content present inside the returned Mojo::DOM object and print it.

Free Resources