英文:
C# Selenium Function to take user input and click on xpath text containing " "?
问题
我正在编写一个函数,该函数应该接受一个字符串,并点击包含与字符串匹配的文本的HTML元素。
但在某些情况下,元素的文本包含特殊字符 ,我的函数无法找到该元素。
我在下面发布了我目前的解决方案,这是我在另一篇帖子中找到的,但这也不起作用。我还尝试过normalize-space,但那只对空格字符有效,而不是 
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&nbsp;Doo&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  , 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  
public static void ClickOnItem(string itemName)
{
IWebElement target = BrowserUtility.FindElement(By.XPath(String.Format("//div[translate(.,'\u00A0','')='{0}']",itemName)));
TestUtility.ClickElement(target);
}
The HTML element I am trying to click on looks like this:
<div>Foo&nbsp;Doo&nbsp;Item</div>
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 = "some user input";
string adjustedInput = input.Replace(" ", " "); // replace space with nb-space
IWebElement target = BrowserUtility.FindElement(By.XPath($"//*[text()='{adjustedInput}']"));
TestUtility.ClickElement(target);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论