6

Is there a similar way in Laravel Dusk as we have in Selenium, to get the source code of an element by 'innerHTML attribute'?

Ex: innerHTML for <div>Hello <p>World!</p></div> would be: Hello <p>World!</p>.

2

2 Answers 2

10

To get source code of element you should use element() method together with getAttribute like this:

$this->browse(function(Browser $browser) {

    $html = $browser->visit('/')
                    ->element('div.content')
                    ->getAttribute('innerHTML');

   // now in $html you have HTML inside div.content element
});

Be aware in case you have multiple elements with given selector you should use elements() method and iterate over found elements to get their content like this:

$this->browse(function(Browser $browser) {
    $elements = $browser->visit('/')
                        ->elements('div.content');

    $html = [];
    foreach ($elements as $element) {
        $html[] = $element->getAttribute('innerHTML');
    }

    // now in $html you have array of HTML inside div.content elements
});
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you. Could you point me to the right Dusk documentation with all available commands / methods. Are 'element' and 'getAttribute' Dusk methods or PHP Selenium commands?
You can look at vendor/laravel/dusk/Concerns files. In InteractsWithElements you will find elements and element methods. But getAttribute method is from FaebookWebDriver - this is located in Facebook\WebDriver\Remote\RemoteWebElement class
Thanks, I found them under vendor/laravel/dusk/src/Concerns/InteractsWithElements.php and vendor/Facebook/WebDriver/lib/Remote/RemoteWebElement.php.
2

I'm not familiar with Selenium innerHTML but with Dusk you can assert directly against the source code via $browser->assertSourceHas($code).

You'll get to see the full source code of your site if the assertion fails.

public function testSourceCode()
    {
        $this->browse(function (Browser $browser) {
            $browser->visit('/')
                    ->assertSourceHas('Hello <p>World!</p>');
        });
    }

1 Comment

By assertSourceHas, you already know the source code, but by innerHTML you get the value of an unknown source code.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.