C# Selenium功能,用于接收用户输入并点击包含” “的XPath文本?

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

C# Selenium Function to take user input and click on xpath text containing " "?

问题

我正在编写一个函数,该函数应该接受一个字符串,并点击包含与字符串匹配的文本的HTML元素。

但在某些情况下,元素的文本包含特殊字符&nbsp,我的函数无法找到该元素。

我在下面发布了我目前的解决方案,这是我在另一篇帖子中找到的,但这也不起作用。我还尝试过normalize-space,但那只对空格字符有效,而不是&nbsp

public static void ClickOnItem(string itemName)
{
    IWebElement target = BrowserUtility.FindElement(By.XPath(String.Format("//div[translate(.,'\u00A0','')='{0}']", itemName)));
    TestUtility.ClickElement(target);
}

我试图点击的HTML元素如下所示:

<div>Foo&amp;nbsp;Doo&amp;nbsp;Item</div>

理想情况下,用户将'Foo Doo Item'传递给函数,函数将点击div元素。

如有可能,请提供帮助,将不胜感激。

英文:

I am writing a function that is supposed to take in a string, and click on the html element containing text matching the string.

But in some cases, the element's text contains the special characters &nbsp, and my function fails to find the element.

I posted my current solution below which I found in another post, but this does not work either. I've also tried normalize-space, but that only works for space characters, and not &nbsp

        public static void ClickOnItem(string itemName)
        {
            IWebElement target = BrowserUtility.FindElement(By.XPath(String.Format(&quot;//div[translate(.,&#39;\u00A0&#39;,&#39;&#39;)=&#39;{0}&#39;]&quot;,itemName)));
            TestUtility.ClickElement(target);
        }

The HTML element I am trying to click on looks like this:

&lt;div&gt;Foo&amp;nbsp;Doo&amp;nbsp;Item&lt;/div&gt;

Ideally, the user would pass 'Foo Doo Item' into the function, and the function would click on the div element.

Any help on if this is possible would be greatly appreciated.

答案1

得分: 1

你需要用不间断空格替换空格。在Windows上,你可以使用Alt+0160键入不间断空格。警告,在你的代码编辑器中,这很可能看起来与普通空格完全相同,因此你的代码的可维护性会降低。

string input = "some user input";
string adjustedInput = input.Replace(" ", "\u00A0"); // 用不间断空格替换空格
IWebElement target = BrowserUtility.FindElement(By.XPath($"//*[text()='{" + adjustedInput + "}']"));
TestUtility.ClickElement(target);
英文:

You will need to replace spaces with non-breaking spaces. You can type a non-breaking space on Windows with Alt+0160. Warning, in your code editor this will likely look exactly the same as a regular space, so the maintainability of your code will go down.

string input = &quot;some user input&quot;;
string adjustedInput = input.Replace(&quot; &quot;, &quot;&#160;&quot;); // replace space with nb-space
IWebElement target = BrowserUtility.FindElement(By.XPath($&quot;//*[text()=&#39;{adjustedInput}&#39;]&quot;));
            TestUtility.ClickElement(target);

huangapple
  • 本文由 发表于 2020年1月4日 01:14:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/59582645.html
匿名

发表评论

匿名网友

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

确定