使用 `cy.request()` 命令如何获取 `meta` 标签和 `script` 标签的内容。

huangapple go评论55阅读模式
英文:

Using `cy.request()` command how to get `meta` tag and `script` tag contents

问题

Using the cy.request() command, you can extract the content of the meta tag and the headline attribute content from the script tag as follows:

cy.request(apiHelper.makeGeneralRequestObject("au/booking-area/zone/blue/")).then(
  (response) => {
    const htmlString = response.body;
    const parser = new DOMParser();
    const parseHtml = parser.parseFromString(htmlString, 'text/html');
    
    const $meta = parseHtml.querySelectorAll('meta');
    $meta.forEach(($elem) => {
      const content = $elem.getAttribute('content');
      // Use 'content' as needed
    });

    const $script = parseHtml.querySelector('script[data-n-head="ssr"]');
    if ($script) {
      const scriptContent = JSON.parse($script.textContent);
      const headline = scriptContent.headline;
      // Use 'headline' as needed
    }
  }
);

This code extracts the content attribute from the meta tag and the headline attribute content from the script tag after making a request and parsing the HTML response.

英文:

Using cy.request() command how to get meta tag and script tag content. Example given below:

<meta data-n-head="ssr" data-hid="og-title" property="og:title" content="Blue zone booking area">

<script data-n-head="ssr" data-hid="nuxt-jsonld-6378ffa8" type="application/ld+json">{"@context":"https://schema.org","@type":"WebPage","headline":"Parcel area for Blue Zone one","url":"https://staging.booking.com/au/booking-area/zone/blue/"}</script>

I have tried cy.wrap($meta) and iterate but it doesn't work ?. Can anyone suggest how can we grab content="Blue zone booking area" attribute from meta tag and headline attribute content from the script tag ?

note : This is not a front end test, that's why I am using cy.request() to make sure that the SEO/SSR are looking good in our website. As google SEO send a request and hit the above url, so then we should make sure that the rendering are looking good. When you use cy.visit() or cy.get() command it will enable the browser javascript and that is not I want

 cy.request(apiHelper.makeGeneralRequestObject("au/booking-area/zone/blue/")).then(
        (response) => {
          const htmlString = response.body;
          const parser = new DOMParser();
          const parseHtml = parser.parseFromString(htmlString, 'text/html');
         const $meta = parseHtml.getElementsByTagName('meta');
        $meta.each(($elem)=>{
        // how to get at here             
      })
    });

答案1

得分: 3

以下是翻译好的部分:

Looks like you are mixing up Cypress/jQuery style with DOM (native) style queries.

这似乎是在混合使用Cypress/jQuery风格和DOM(原生)风格的查询。

This should do it using the DOM parser

这应该使用DOM解析器来实现

Or with Cypress (arguably better if performing SEO)

或者使用Cypress(如果进行SEO可能更好)

Also consider Bahmutov - Cypress Lighthouse Example. There is a SEO section in Lighthouse, and the results for https://www.booking.com/au currently show

还要考虑Bahmutov - Cypress Lighthouse Example。Lighthouse中有一个SEO部分,目前显示https://www.booking.com/au的结果如下

No <meta name="viewport"> tag found

未找到<meta name="viewport">标签

jsonLD

There is an example of jsonLD test here cypress-automated-test-for-seo-data

这里有一个jsonLD测试的示例cypress-automated-test-for-seo-data

it("Verify jsonLD structured data - simple", () => {
// Query the script tag with type application/ld+json
cy.get("script[type='application/ld+json']").then((scriptTag) => {
// we need to parse the JSON LD from text to a JSON to easily test it
const jsonLD = JSON.parse(scriptTag.text());

// once parsed we can easily test for different data points
expect(jsonLD["@context"]).equal("https://schema.org");
expect(jsonLD.author).length(2);

// Cross referencing SEO data between the page title and the headline
// in the jsonLD data, great for dynamic data
cy.title().then((currentPageTitle) =>
  expect(jsonLD["headline"]).equal(currentPageTitle)
)

})
})

it("验证jsonLD结构化数据 - 简单", () => {
// 查询带有类型application/ld+json的脚本标签
cy.get("script[type='application/ld+json']").then((scriptTag) => {
// 我们需要将JSON LD从文本解析为JSON以轻松测试
const jsonLD = JSON.parse(scriptTag.text());

// 解析后,我们可以轻松测试不同的数据点
expect(jsonLD["@context"]).equal("https://schema.org");
expect(jsonLD.author).length(2);

// 在页面标题和jsonLD数据的标题之间进行SEO数据的交叉引用,非常适合动态数据
cy.title().then((currentPageTitle) =>
  expect(jsonLD["headline"]).equal(currentPageTitle)
)

})
})

英文:

Looks like you are mixing up Cypress/jQuery style with DOM (native) style queries.

This should do it using the DOM parser

cy.request({
  url: &#39;https://www.booking.com/au&#39;,
  failOnStatusCode: false
}).then(response =&gt; {
  
  const parser = new DOMParser()
  const doc = parser.parseFromString(response.body, &#39;text/html&#39;)
  
  const metaTags = doc.head.querySelectorAll(&#39;meta&#39;) // pull &lt;meta&gt; from document head

  metaTags.forEach(metaTag =&gt; {      // it&#39;s a DOMList, use forEach()
    const key = metaTag.name         // not all have a &quot;name&quot;  
    const content = metaTag.content  // all will have content
    console.log(key, content)
  })
})

Or with Cypress (arguably better if performing SEO)

cy.visit(&#39;https://www.booking.com/au&#39;)
cy.document().then(doc =&gt; {
  cy.wrap(doc.head).find(&#39;meta&#39;).each($meta =&gt; {
    const key = $meta.attr(&#39;name&#39;)
    const content = $meta.attr(&#39;content&#39;)
    console.log(key, content)
  })
})

Also consider Bahmutov - Cypress Lighthouse Example. There is a SEO section in Lighthouse, and the results for https://www.booking.com/au currently show

> No &lt;meta name=&quot;viewport&quot;&gt; tag found

使用 `cy.request()` 命令如何获取 `meta` 标签和 `script` 标签的内容。


jsonLD

There is an example of jsonLD test here cypress-automated-test-for-seo-data

it(&quot;Verify jsonLD structured data - simple&quot;, () =&gt; {
  // Query the script tag with type application/ld+json
  cy.get(&quot;script[type=&#39;application/ld+json&#39;]&quot;).then((scriptTag) =&gt; {
    // we need to parse the JSON LD from text to a JSON to easily test it
    const jsonLD = JSON.parse(scriptTag.text());

    // once parsed we can easily test for different data points
    expect(jsonLD[&quot;@context&quot;]).equal(&quot;https://schema.org&quot;);
    expect(jsonLD.author).length(2);

    // Cross referencing SEO data between the page title and the headline
    // in the jsonLD data, great for dynamic data
    cy.title().then((currentPageTitle) =&gt;
      expect(jsonLD[&quot;headline&quot;]).equal(currentPageTitle)
    )
  })
})

huangapple
  • 本文由 发表于 2023年2月8日 08:43:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/75380386.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定