C# Selenium通过XPath查找元素返回null。

huangapple go评论85阅读模式
英文:

C# Selenium findElements by XPath returns null

问题

IList<IWebElement> firstname = driverOne.FindElements(By.XPath("//*[@id="+ ((char)34) + "4cd85da6-f2d1-4361-9864-e187dc763f9b" + ((char)34) + "]"));

我尝试使用上面的代码从下面的HTML中获取元素,但它返回null,因为每次重新加载页面时XPath会更改,因为元素是通过Angular随机创建的,我认为。

<input id="0bad9cfd-028d-404c-a498-17a3f5f1ae81" type="text" data-test="first-name-input" placeholder="" class="ng-untouched ng-pristine ng-invalid"><!----><!---->

我还尝试使用Id和CSS选择器,但在重新加载后一切都会更改,所以我不知道该怎么办...

那么,我该如何获取这个元素?

英文:
IList<IWebElement> firstname = driverOne.FindElements(By.XPath("//*[@id="+ ((char)34) + "4cd85da6-f2d1-4361-9864-e187dc763f9b" + ((char)34) + "]"));

I tried this go get the element from the HTML below, but it returns null, because everytime I reload the page the XPath gets changed, because the element gets created randomly from Angular, I think.

<input id="0bad9cfd-028d-404c-a498-17a3f5f1ae81" type="text" data-test="first-name-input" placeholder="" class="ng-untouched ng-pristine ng-invalid"><!----><!---->

I also tried to do it with the Id and the CSS-Selector, but everything is changed after a reload, so I dont know what do...

So how can I get the Element?

答案1

得分: 0

"try using data-test maybe?"

firstname = driver.FindElement(By.XPath("//*[@data-test='first-name-input']"));
英文:

try using data-test maybe?

firstname =driver.FindElement(By.XPath("//*[@data-test='first-name-input']"));

答案2

得分: 0

当你严格地为HTML标签分配一个ID,如:

<h1 id="test"></h1>

在Angular渲染过程后,ID将不会改变。你可以为需要访问的每个元素添加ID。

英文:

When you assign an ID to html tag strictly like:

&lt;h1 id=&quot;test&quot;&gt; &lt;/h1&gt;

ID will not change after Angular rendering process. You can add Id's to every element you need to access.

huangapple
  • 本文由 发表于 2020年1月6日 21:57:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/59613414.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定