Search code examples
karate

API returns HTML response - how to extract value from Head > Meta tag by name?


The HTML the url returns is:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="csrf-token" content="I-need-this-value/>
</head>

I found a few similar questions

This one seemed like I could store the response as responseBytes and find it that way, but that didn't work.

And then this answer which I implemented like :


  Background:
#   call auth with shared scope
    * call read('classpath:util/auth.feature')
    * def dashboard = 'https://ourURL.com/dashboard'


  Scenario: get csrf-token
    Given url dashboard
    When method get
    * def responseHtml = response
    * def csrfToken = karate.extract(responseHtml, 'csrf-token.text=\\"([^\\"]+)', 1)
    * print csrfToken

which returns

14:05:02.696 [main] WARN  com.intuit.karate - failed to find pattern: csrf-token.text=\"([^\"]+)
14:05:02.698 [main] INFO  com.intuit.karate - [print] null

I have tried storing the response as a string first:

    Given url dashboard
    When method get
    * def responseHtml = response
    * string responseString = responseHtml
    * def csrfToken = karate.extract(responseString, 'csrf-token.text=\\"([^\\"]+)', 1)
    * print csrfToken

but it returns the same error.

Has anyone done this before?

I also realize I could do this via the karate UI and tried to do it that way but also couldn't get it to work:

  Scenario: get csrf-token
    Given driver 'https://ourURL.com/dashboard'
    Then match driver.title == 'Dashboard'
    * def e = text('meta[name=csrf-token')
    * print 'e is ' + e

print statement is [print] e is null


Solution

  • I should have read further - script() allows you to do javascript like document.getelement - etc

    so for anyone needing to do this in the future

        Given driver 'https://ourURL.com/dashboard'
        Then match driver.title == 'Dashboard'
        * def token = script("document.querySelector('meta[name=\"csrf-token\"]').content")
        * print 'token is ' + token