Repository: yt-dlp/yt-dlp
File: yt_dlp/extractor/facebook.py (Python)

Code before:

    def _real_extract(self, url):
        video_id = self._match_id(url)
        webpage = self._download_webpage(url, video_id)

        if post_data := [self._parse_json(j, video_id, fatal=False)
                         for j in re.findall(r'data-sjs>({.*?ScheduledServerJS.*?})</script>', webpage)]:
            data = traverse_obj(post_data, (
                ..., 'require', ..., ..., ..., '__bbox', 'require', ..., ..., ...,
                'entryPointRoot', 'otherProps', 'deeplinkAdCard', 'snapshot', {dict}), get_all=False)
        elif post_data := [self._parse_json(j, video_id, fatal=False)
                           for j in re.findall(r's\.handle\(({.*})\);requireLazy\(', webpage)]:
            data = traverse_obj(post_data, (
                ..., 'require', ..., ..., ..., 'props', 'deeplinkAdCard', 'snapshot', {dict}), get_all=False)
        if not data:
            raise ExtractorError('Unable to extract ad data')

        title = data.get('title')
        if not title or title == '{{product.name}}':
            title = join_nonempty('display_format', 'page_name', delim=' by ', from_dict=data)
        markup = None
        if markup_id := traverse_obj(data, ('body', '__m', {str_or_none}), get_all=False):
            markup = clean_html(traverse_obj(post_data, (
                ..., 'require', ..., ..., ..., '__bbox', 'markup', lambda _, v: v[0].startswith(markup_id),
                ..., '__html', {lambda x: x if x and not x.startswith('&#123;&#123;product.') else None}),
                get_all=False))

        info_dict = traverse_obj(data, {
            'title': ({lambda x: title}),
            'description': ('link_description', {lambda x: markup or (x if x and not x.startswith('{{product.') else None)}),
            'uploader': ('page_name', {str}),
            'uploader_id': ('page_id', {str_or_none}),
            'uploader_url': ('page_profile_uri', {url_or_none}),
            'timestamp': ('creation_time', {int_or_none}),
            'like_count': ('page_like_count', {int_or_none}),
        })

        entries = []
        for idx, entry in enumerate(traverse_obj(
            data, (('videos', 'cards'), lambda _, v: any(url_or_none(v.get(f)) for f in self._FORMATS_MAP))), 1,
        ):
            entries.append({
                'id': f'{video_id}_{idx}',
                'title': entry.get('title') or title,
                'description': entry.get('body') or entry.get('link_description') or info_dict.get('description'),
                'thumbnail': url_or_none(entry.get('video_preview_image_url')),
                'formats': self._extract_formats(entry),
            })

        if len(entries) == 1:
            info_dict.update(entries[0])

Review comment (refactor):
Let's also simplify this... get rid of the assignment expression and instead just rely on traversal catching the `.startswith(None)` error and returning `None`. (We shouldn't be using `str_or_none` in the `markup_id` traversal path anyways, expecting the type is better). We can also transform with `clean_html` inside the `markup` traversal path, which makes everything a bit easier to read:

```suggestion
        markup_id = traverse_obj(data, ('body', '__m', {str}))
        markup = traverse_obj(post_data, (
            ..., 'require', ..., ..., ..., '__bbox', 'markup', lambda _, v: v[0].startswith(markup_id),
            ..., '__html', {clean_html}, {lambda x: not x.startswith('{{product.') and x}, any))
```

Code after:

    def _real_extract(self, url):
        video_id = self._match_id(url)
        webpage = self._download_webpage(url, video_id)

        post_data = traverse_obj(
            re.findall(r'data-sjs>({.*?ScheduledServerJS.*?})</script>', webpage), (..., {json.loads}))
        data = get_first(post_data, (
            'require', ..., ..., ..., '__bbox', 'require', ..., ..., ...,
            'entryPointRoot', 'otherProps', 'deeplinkAdCard', 'snapshot', {dict}))
        if not data:
            raise ExtractorError('Unable to extract ad data')

        title = data.get('title')
        if not title or title == '{{product.name}}':
            title = join_nonempty('display_format', 'page_name', delim=' by ', from_dict=data)
        markup_id = traverse_obj(data, ('body', '__m', {str}))
        markup = traverse_obj(post_data, (
            ..., 'require', ..., ..., ..., '__bbox', 'markup', lambda _, v: v[0].startswith(markup_id),
            ..., '__html', {clean_html}, {lambda x: not x.startswith('{{product.') and x}, any))

        info_dict = merge_dicts({
            'title': title,
            'description': markup or None,
        }, traverse_obj(data, {
            'description': ('link_description', {lambda x: x if not x.startswith('{{product.') else None}),
            'uploader': ('page_name', {str}),
            'uploader_id': ('page_id', {str_or_none}),
            'uploader_url': ('page_profile_uri', {url_or_none}),
            'timestamp': ('creation_time', {int_or_none}),
            'like_count': ('page_like_count', {int_or_none}),
        }))

        entries = []
        for idx, entry in enumerate(traverse_obj(
            data, (('videos', 'cards'), lambda _, v: any(url_or_none(v.get(f)) for f in self._FORMATS_MAP))), 1,
        ):
            entries.append({
                'id': f'{video_id}_{idx}',
                'title': entry.get('title') or title,
                'description': traverse_obj(entry, 'body', 'link_description') or info_dict.get('description'),
                'thumbnail': url_or_none(entry.get('video_preview_image_url')),
                'formats': self._extract_formats(entry),
            })

        if len(entries) == 1:
            info_dict.update(entries[0])

        elif len(entries) > 1:
            info_dict.update({
                'title': entries[0]['title'],