17
17
use Facebook \WebDriver \WebDriver ;
18
18
use Facebook \WebDriver \WebDriverBy ;
19
19
use Facebook \WebDriver \WebDriverElement ;
20
+ use Symfony \Component \CssSelector \CssSelectorConverter ;
20
21
use Symfony \Component \DomCrawler \Crawler as BaseCrawler ;
21
22
use Symfony \Component \Panther \ExceptionThrower ;
22
23
@@ -154,9 +155,15 @@ public function parents()
154
155
/**
155
156
* @see https://github.com/symfony/symfony/issues/26432
156
157
*/
157
- public function children ()
158
+ public function children (string $ selector = null )
158
159
{
159
- return $ this ->createSubCrawlerFromXpath ('child::* ' );
160
+ $ xpath = 'child::* ' ;
161
+ if (null !== $ selector ) {
162
+ $ converter = $ this ->createCssSelectorConverter ();
163
+ $ xpath = $ converter ->toXPath ($ selector , 'child:: ' );
164
+ }
165
+
166
+ return $ this ->createSubCrawlerFromXpath ($ xpath );
160
167
}
161
168
162
169
public function attr ($ attribute ): string
@@ -174,16 +181,32 @@ public function nodeName(): string
174
181
return $ this ->getElementOrThrow ()->getTagName ();
175
182
}
176
183
177
- public function text (): string
184
+ public function text ($ default = null ): string
178
185
{
179
- return $ this ->getElementOrThrow ()->getText ();
186
+ try {
187
+ return $ this ->getElementOrThrow ()->getText ();
188
+ } catch (\InvalidArgumentException $ e ) {
189
+ if (null === $ default ) {
190
+ throw $ e ;
191
+ }
192
+
193
+ return (string ) $ default ;
194
+ }
180
195
}
181
196
182
- public function html (): string
197
+ public function html ($ default = null ): string
183
198
{
184
- $ this ->getElementOrThrow ();
199
+ try {
200
+ $ this ->getElementOrThrow ();
201
+
202
+ return $ this ->attr ('outerHTML ' );
203
+ } catch (\InvalidArgumentException $ e ) {
204
+ if (null === $ default ) {
205
+ throw $ e ;
206
+ }
185
207
186
- return $ this ->attr ('outerHTML ' );
208
+ return (string ) $ default ;
209
+ }
187
210
}
188
211
189
212
public function evaluate ($ xpath ): self
@@ -453,4 +476,16 @@ public function findElements(WebDriverBy $locator)
453
476
{
454
477
return $ this ->getElementOrThrow ()->findElements ($ locator );
455
478
}
479
+
480
+ /**
481
+ * @throws \LogicException If the CssSelector Component is not available
482
+ */
483
+ private function createCssSelectorConverter (): CssSelectorConverter
484
+ {
485
+ if (!class_exists (CssSelectorConverter::class)) {
486
+ throw new \LogicException ('To filter with a CSS selector, install the CssSelector component ("composer require symfony/css-selector"). Or use filterXpath instead. ' );
487
+ }
488
+
489
+ return new CssSelectorConverter ();
490
+ }
456
491
}
0 commit comments