简体   繁体   English

c# selenium 无法检测到元件

[英]c# selenium cannot detect element

I want to logout from reddit using selenium in c#.我想在 c# 中使用 selenium 从 reddit 注销。 And I have a little problem and I hope somebody can help me.我有一个小问题,我希望有人能帮助我。 This is my following code in c#:这是我在 c# 中的以下代码:

               var profile = Driver.FindElement(By.XPath("span[@class='DFKWwVItcycZV1bKUOyay']"));
//^is for oppening this dropdown menue | https://i.imgur.com/d8r4C6D.png
                profile.Click();
               var logout = Driver.FindElement(By.XPath("div[@class='vzhy90YD0qH7ZDJi7xMGw']"));
//to press on logout | https://i.imgur.com/ON2A92f.png
                logout.Click();

how the website source look like:网站源代码的样子:

<span class="DFKWwVItcycZV1bKUOyay">
[...]
<div class="vzhy90YD0qH7ZDJi7xMGw">Log Out</div>

It would better for checking the reddit source itself.最好检查 reddit 源本身。

Thank you for reading this谢谢您阅读此篇

Your XPaths are not valid.您的 XPath 无效。 They should start with // , eg它们应该以//开头,例如

//div[@class='vzhy90YD0qH7ZDJi7xMGw']

The second issue is that the class you are referencing is likely randomly generated and will change often.第二个问题是您引用的 class 可能是随机生成的,并且会经常更改。 I would use the "Log Out" text to find the right element.我会使用“注销”文本来找到正确的元素。

Driver.FindElement(By.Id("email-collection-tooltip-id")).Click(); // opens the menu
Driver.FindElement(By.XPath("//a/div[text()='Log Out']")).Click(); // logs out

You might want to try clicking the element above this which is a link.您可能想尝试单击此链接上方的元素。

<a data-redditstyle="true" class="randomstring" href="/"><svg></svg><div class="vzhy90YD0qH7ZDJi7xMGw">Log Out</div></a>

As mjwills mentioned, that class is certain to change one day and will likely break the code.正如 mjwills 所提到的,class 肯定有一天会改变,并且可能会破坏代码。 Take another approach by possibly looking for the text "Log Out" then working backwards to the element you want.采取另一种方法,可能会查找文本“注销”,然后返回到您想要的元素。

Sometime few elements are not set as displayed true in DOM, in that case we need to click that element forcefully.有时很少有元素在 DOM 中未设置为显示为 true,在这种情况下,我们需要强制单击该元素。 Actions class is an ability provided by Selenium for handling keyboard and mouse events. Actions class 是 Selenium 提供的用于处理键盘和鼠标事件的能力。

var logout = Driver.FindElement(By.Id("DemoAutomationID")); 
Actions action = new Actions(driver);
action.MoveToElement(logout).Click().Perform(); 
//or 
action.MoveToElement(logout).Click().Build().Perform();

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

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