简体   繁体   English

使用 javascript 解析 html 文本的一部分

[英]Parsing part of a html text using javascript

The output on my page after generating a certain link is:生成某个链接后我页面上的output是:

    <string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">
SUCCESS|78502|25cca4bc-08f9-4a59-85f8-64e0d0700924|
</string>

What i'm interested in is the 78502 because it's an unique id i need to use in later protractor tests.我感兴趣的是 78502,因为它是我需要在以后的 protractor 测试中使用的唯一 ID。

This is the html part of it.这是它的 html 部分。

<span xmlns="http://www.w3.org/1999/xhtml" class="text">SUCCESS|78502|25cca4bc-08f9-4a59-85f8-64e0d0700924|</span>

I'm prety blocked atm since i've never done something like this, the first step i took was getting the xpath of the html element and applying the getText method on it and console.log-ing it to check that i can at least get the value but that doesn't seem to give me the value of the element.因为我从来没有做过这样的事情,所以我很容易阻塞 atm,我采取的第一步是获取 html 元素的 xpath 并在其上应用 getText 方法和 console.log-ing 以检查我至少可以获得价值,但这似乎并没有给我元素的价值。 Any materials/links that can help me better understand what i need to do is appreciated!任何可以帮助我更好地理解我需要做的事情的材料/链接都值得赞赏!

Is that html element unique?那个 html 元件是独一无二的吗? If there isn't any other with same xmlns attribute and same class you can get that with pure Javascript:如果没有任何其他具有相同的 xmlns 属性和相同的 class 您可以使用纯 Javascript 获得:

// Get text inside the element
var text = document.querySelector('span.text[xmlns="http://www.w3.org/1999/xhtml"]').innerText;

// Get an array of the parts ["SUCCESS", "78502" ...]
var text_parts = text.split('|');
console.log(text_parts);

// If that array has a second element (that id) get that second element
var id = '';
if (text_parts.length >= 2) id = text_parts[1];
console.log(id);

If there's a way to generate that html with an id so it's unique it would be more safe, so you are sure the querySelector will pick the right one.如果有一种方法可以生成带有 id 的 html ,那么它会更安全,因此您确信 querySelector 会选择正确的。 So if you have所以如果你有

<span id="span-with-id" xmlns="http://www.w3.org/1999/xhtml" class="text">SUCCESS|78502|25cca4bc-08f9-4a59-85f8-64e0d0700924|</span>

you could use你可以使用

var text = document.querySelector('#span-with-id').innerText;

Note that you have to do that with Javascript, after this HTML element is inserted into the document.请注意,在将此 HTML 元素插入文档后,您必须使用 Javascript 执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM