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>
.
Method #1 – Read the innerHTML attribute to get the source of the content of the element. innerHTML is a property of a DOM element whose value is the HTML that exists in between the opening tag and ending tag. For example, the innerHTML property in the code below carries the value “ text ” <p> a text </p>
We can obtain the html source of the webelement with the help of Javascript Executor. We shall utilize the execute_script method and pass arguments index.innerHTML and webelement whose html source is to be retrieved to the method. Let us see the below html code of an element.
Nearly every webpage you come across uses HTML to structure and display HTML pages. You can inspect the source code of any webpage by using a web browser like Firefox or Chrome. On Firefox, navigate to the “Tools” menu item in the top menu and click on “Web Developer/Page Source” like so:
If you've use Inspect element, you should see the code for that part highlighted. To view other parts of the code, or if you got to Developer Tools using F12, click the icon with the rectangle and weird triangle in the top left corner of the Developer Tools window. Move your mouse to hover over the area you want to see.
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
});
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>');
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With