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>.

Marcin Nabiałek
  • 109,655
  • 42
  • 258
  • 291
shaebi
  • 99
  • 2
  • 10
  • Didn't this help ? [get-html-source-of-webelement-in-selenium-webdriver-using-python](https://stackoverflow.com/questions/7263824/get-html-source-of-webelement-in-selenium-webdriver-using-python) – hamzagiveshugs Oct 03 '17 at 14:58
  • I am looking for a Dusk solution. – shaebi Oct 04 '17 at 06:45

2 Answers2

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
});
Marcin Nabiałek
  • 109,655
  • 42
  • 258
  • 291
  • 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? – shaebi Oct 08 '17 at 08:41
  • 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 – Marcin Nabiałek Oct 08 '17 at 08:46
  • 1
    Thanks, I found them under `vendor/laravel/dusk/src/Concerns/InteractsWithElements.php` and `vendor/Facebook/WebDriver/lib/Remote/RemoteWebElement.php`. – shaebi Oct 08 '17 at 10:08
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>');
        });
    }
Sven
  • 1,450
  • 3
  • 33
  • 58
  • By assertSourceHas, you already know the source code, but by innerHTML you get the value of an unknown source code. – shaebi Oct 04 '17 at 05:32