简体   繁体   English

CssSelector无法通过ID查找元素(Selenium Webdriver C#)

[英]CssSelector cannot find element by Id (selenium webdriver C#)

I use simple code as 我使用简单的代码作为

 [FindsBy(How = How.CssSelector, Using = "div[id=1]")]
 private IWebElement _plasticOption;

to find element with id = 1. 查找id = 1的元素。

It's for page factory, if someone don't know what it is, we can change the code above to the next one: 它用于页面工厂,如果有人不知道它是什么,我们可以将上面的代码更改为下一个:

 IWebElement element = driver.FindElement(By.CssSelector("div[id=1]"));

So, this simple code can't find an element in the next piece of HTML: 因此,此简单的代码无法在下一部分HTML中找到元素:

<div class="b-wide-option disabled" data-bind="css: { selected: IsSelected, disabled: !IsVisible() }, click: Select, attr: { id: Id }" id="1"> </div>

But I can simply find this element the next way: 但是我可以通过以下方式简单地找到此元素:

 [FindsBy(How = How.Id, Using = "1")]
 private IWebElement _plasticOption;

And I actually wonder why I can't find this element using CssSelector. 我实际上想知道为什么我无法使用CssSelector找到该元素。

I have: 我有:

selenium webdriver v.2.43.1 硒webdriver v.2.43.1

chromedriver v. 2.10 chromedriver v。2.10

Chrome Brovser v. 37.0.2062.120 Chrome Brovser v.37.0.2062.120

[id=1] is not a valid attribute selector. [id=1]不是有效的属性选择器。 When the attribute value is unquoted, it's treated as a CSS identifier, and a CSS identifier cannot start with a digit . 如果属性值未加引号,则将其视为CSS标识符,并且CSS标识符不能以digit开头 It is for this same reason that a selector like div#1 will not work. 出于同样的原因,像div#1这样的选择器将不起作用。

If you need to look for an attribute value that starts with a digit, you need to quote the value: 如果需要查找以数字开头的属性值,则需要引用该值:

[FindsBy(How = How.CssSelector, Using = "div[id='1']")]
private IWebElement _plasticOption;

If you prefer to use an ID selector, you need to escape the digit (you could also do this in the attribute selector, but you'd be better off just quoting the value instead): 如果您更喜欢使用ID选择器,则需要对数字进行转义(您也可以在属性选择器中执行此操作,但是最好只引用该值):

[FindsBy(How = How.CssSelector, Using = "div#\\1")]
private IWebElement _plasticOption;

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

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