【发布时间】:2017-09-28 23:28:20
【问题描述】:
我正在尝试为具有 4 个按钮的相同代码的按钮创建 Selenium 测试(以下 html 重复 4 次):
<div class="item">
<div class="head">
<a class="title caps_style primary-color-text"href="https://www.www.www/link/link-link-complex-api-testing" target="_blank">Rake Athlete Complex API TESTING</a>
</div>
<div class="middle">
<div class="photo_square">
<a class="" href="https://www.www.www/link/link-link-complex-api-testing" target="_blank"><img src="/assets/2.png"></a>
</div>
<span class="stats">
<span class="title caps_style votes">salvations</span>
<span class="amt caps_style primary-color-text">
<i class="heart"></i><!-- react-text: 58 -->240
<!-- /react-text -->
</span>
</span>
<div class="stats">
<span class="title caps_style">Pickles Grazed</span>
<span class="amt caps_style primary-color-text">
<span class="fastack"><i class="fastack2x"></i>
<i class="fainverse"></i></span>
<i class="usb"></i><!-- react-text: 66 -->184 k<!-- /react-text -->
</span>
</div>
</div>
<div class="bottom">
<span class="snippit">latin fillin text</span>
</div>
<div class="inline-b">
<div>
<button class="vote-btn primary-color-background">
<img src="//www.www.www/assets/pic.png">
<span class="primary-color-background">Give</span>
</button>
</div>
</div>
这是我尝试为第一个按钮(CssSelector 和 XPath)运行的 C# 代码:
driver.FindElement(By.CssSelector("button.vote-btn.primary-color-background")).Click();
还有:
driver.FindElement(By.XPath("//*[@id='Sections-react-component-0']/div/div[3]/div/div[1]/div[1]/div[4]/div/button").Click();
我在进行 Selenium 测试时收到以下错误消息:
Message: System.InvalidOperationException : unknown error: Element <button class="vote-btn primary-color-background">...</button> is not clickable at point (286, 1233).
Other element would receive the click: <p>...</p>
(Session info: chrome=61.0.3163.100)
(Driver info: chromedriver=2.32.498550
是否可以使用 CssSelector 选择特定选项?例如在代码中的某处使用 [2] 或 [4]?
【问题讨论】:
-
1.对于 css 选择器,它具有与 xpath 的 [index] 相似的功能。但比 xpath 更严格。在 CSS 选择器中,您可以使用 :nth-child(index) index >=1 或 nth-of-type(index) index>=1。但 nth-child() 要求它们具有相同的父节点,但 xpath 不需要。
-
从您的代码中,css 选择器是正确的。但你遇到了错误:'元素不可点击,其他元素会收到点击'。这个错误意味着有一些东西覆盖了你要点击的按钮,下层的按钮,所以上层的元素会收到点击。您可以在运行期间检查按钮顶部是否有任何东西。如果没有,你需要等待页面加载完成,因为页面加载时按钮位置可能会发生变化,所以你会点击一个不是按钮最新位置的旧点。
-
为什么不直接使用索引呢?如果有 4 个按钮,则为“sameCode[1]、sameCode[2]、sameCode[3]、sameCode[4]”。显然这是使用 xPath,但你可以在 CssSelector 中做类似的事情,我认为它是使用 nth-child 的“sameCode(1)..etc 等”。
-
谢谢两位,我会调查的。我对 C# 很陌生,我仍在尝试掌握格式。另外,yong,我尝试添加一个 Thread.Sleep(1000) 以使页面有足够的时间加载,但当前代码仍然失败。我还想指出,代码昨天运行良好,我需要把那个贴纸贴在我的笔记本电脑上。大声笑
标签: c# selenium xpath css-selectors