【问题标题】:How to grab HTML tags as well as the text between them and store in an object如何获取 HTML 标签以及它们之间的文本并存储在对象中
【发布时间】:2018-05-13 20:41:02
【问题描述】:

我正在开发一个 selneium-appium-java 移动网络自动化框架。我有一个黄瓜测试,它使用正则表达式来接受一些文本并将其作为参数进一步传递,例如:

@Given("^user checks text \"([^\"]*)\" in footer$")
public void checkFooter(String footerText) {
    footerComponent.checkNote(footerText);
}

这是当前在 FooterComponent 类中查找节点基本文本的设置方式

    private final String FOOTER = "//div[contains(@class, 'footer')]";

    public void checkNote(String expectedText) {
    By note = By.xpath(FOOTER + "//div[@class='footer-footnote']");
    String actualText = getDriver().findElement(footerText).getText();
    assertEquals(actualText, expectedText, "Unexpected footer note");
}

我需要验证预期结果的 DOM 示例:

<div class='footer'>
text1
<span class="copysymbol"></span>
text2
<span class="dot"></span>
text3
<span class="dot"></span>
text4
<span class="dot"></span>
</div>

我尝试使用此处的模式,但没有成功: https://alvinalexander.com/blog/post/java/how-extract-html-tag-string-regex-pattern-matcher-group

所以基本上我需要插入一些文本来检查标签是否存在(代表我需要检查的特殊字符)以及它们之间的文本在黄瓜行中,然后让 java 方法检查实际代码通过使用 Xpath 找到它。有没有办法通过黄瓜使用正则表达式来完成?

【问题讨论】:

  • 我认为使用 xPath 检查 HTML 比使用正则表达式要好得多。所以也许你可以在这里继续使用 xPath。

标签: java regex selenium-webdriver automation appium


【解决方案1】:

我喜欢提供一个存根作为答案,因为我必须同意 XPath 在这里比正则表达式更合适。
另外,如果这里有人给你一个复杂的正则表达式,它可以做你想做的所有事情,但你无法维护......你有什么收获?

以下模式匹配整个页脚 div。我不能做更多,因为你的描述只包含一个例子,没有变化。

&lt;div class='footer'&gt;.*?&lt;span class="copysymbol"&gt;&lt;\/span&gt;.*?&lt;span class="dot"&gt;&lt;\/span&gt;.*?&lt;span class="dot"&gt;&lt;\/span&gt;.*?&lt;span class="dot"&gt;&lt;\/span&gt;\s*&lt;\/div&gt;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

final String regex = "<div class='footer'>.*?<span class=\"copysymbol\"><\\/span>.*?<span class=\"dot\"><\\/span>.*?<span class=\"dot\"><\\/span>.*?<span class=\"dot\"><\\/span>\\s*<\\/div>";
final String string = "<div class='footer'>\n"
     + "text1\n"
     + "<span class=\"copysymbol\"></span>\n"
     + "text2\n"
     + "<span class=\"dot\"></span>\n"
     + "text3\n"
     + "<span class=\"dot\"></span>\n"
     + "text4\n"
     + "<span class=\"dot\"></span>\n"
     + "</div>";

final Pattern pattern = Pattern.compile(regex, Pattern.DOTALL);
final Matcher matcher = pattern.matcher(string);

while (matcher.find()) {
    System.out.println("Full match: " + matcher.group(0));
    for (int i = 1; i <= matcher.groupCount(); i++) {
        System.out.println("Group " + i + ": " + matcher.group(i));
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 2020-06-26
    • 1970-01-01
    • 2020-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多