Functions/Get-Puppeteer_RetrieveTextFromSelector.ps1

<#
.SYNOPSIS
    This function returns the Node JS Puppeteer code for retrieving text from a selector on a browser page.
#>

function Get-Puppeteer_RetrieveTextFromSelector {
    [CmdletBinding(PositionalBinding=$true)]
    [OutputType([String])]
    param (
        # The name of the selector.
        [Parameter(Mandatory=$true)]
        [ValidateNotNullOrEmpty()]
        [String]$selectorName,

        # The variable to save the text in.
        [Parameter(Mandatory=$true)]
        [ValidateNotNullOrEmpty()]
        [String]$variableName
    )

    # Generate the code
    $code = @"
selector = '%selectorName%'
await page.waitForSelector(selector);
%variableName% = await page.evaluate(selector => {
    const anchors = Array.from(document.querySelectorAll(selector));
    return anchors.map(anchor => { return anchor.textContent; });
}, selector);
"@

    $code = $code -replace "%selectorName%", $selectorName
    $code = $code -replace "%variableName%", $variableName

    # Return the code
    return $code
}