Selenium为什么将反斜杠附加到点号(.)字符后,导致点号(.)成为其中包含(.)的ID属性值的(\.) [英] Why does Selenium appends a back slash to the dot (.) character resulting into (\.) for the value of ID attribute that has a (.) in it

查看:137
本文介绍了Selenium为什么将反斜杠附加到点号(.)字符后,导致点号(.)成为其中包含(.)的ID属性值的(\.)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用JAVA中的硒元素通过ID来获取元素.当我尝试像这样找到元素

I want to get an element by ID with selenium in JAVA. The ID of the element in question so happens to have a period in it id="myprojectId0.123456789" when I try to find the element like so

WebElement projId = driver.findElement(By.id("mprojectId0.10724909303153396"));

我在控制台中收到此错误:

I get this error in the console:

Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to locate element: #mprojectId0\.10724909303153396

由于某些原因, ID 属性值内的.字符被转换为\.,因此无法找到该元素.请先帮助并谢谢!!

For some reason the . character within the value of the ID attribute is being converted to \. and hence it cannot find the element. Please help and thanks in advance!

推荐答案

您的观察非常合理,符合预期.根据 Webdriver的官方定位器策略 < Selenium 将c3>转换为等效的 By.cssSelector ,并且由于 . 字符是特殊字符,因此会自动通过反斜杠 转义,即 \ .因此:

Your observation is pretty much justified and as expected. As per the discussion in Official locator strategies for the webdriver By.id is translated by Selenium into it's equivalent By.cssSelector and as the . character is a special character, it is automatically escaped by a backslash i.e. \. Hence:

By.id("mprojectId0.10724909303153396")

被翻译成

By.cssSelector("#mprojectId0\.10724909303153396")


解决方案

但是id 属性的值(即 mprojectId0.10724909303153396 )对我来说似乎是动态的,并且每次


Solution

However the value of the id attribute i.e. mprojectId0.10724909303153396 looks dynamic to me and would change everytime the HTML DOM gets rendered. Accordingly you have to induce WebDriverWait for the visibilityOfElementLocated() and you can use either of the following dynamic Locator Strategies:

  • cssSelector:

WebElement projId = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("[id^='mprojectId']")));

  • xpath:

    WebElement projId = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[starts-with(@id, 'mprojectId')]")));
    

  • 这篇关于Selenium为什么将反斜杠附加到点号(.)字符后,导致点号(.)成为其中包含(.)的ID属性值的(\.)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆