Selenium: How to find element by partial href?

*爱你&永不变心* 提交于 2019-12-06 02:21:56

问题


Working code 1:

Driver.Instance.FindElement( By.XPath("//a[contains(@href,'" + PartialLinkHref + "')]" ));

Working code 2:

ReadOnlyCollection<IWebElement> linkList = Driver.Instance.FindElements(By.TagName("a"));
for (int i = 0; i < linkList.Count ; i++)
{
     if (linkList[1].GetAttribute("href").Contains(PartialLinkHref))
     {
          element.SetElement(linkList[i]);
          return element;
          break;
     }
}

回答1:


The problem with your initial selector is that you're missing the // in front of the selector. the // tells XPath to search the whole html tree.

This should do the trick:

Driver.Instance.FindElement(By.XPath("//a[contains(@href, 'long')]"))

If you want to find children of an element, use .// instead, e.g.

var element = Driver.Instance.FindElement("..some selector..")
var link = element.FindElement(".//a[contains(@href, 'long')]"))

If you want to find a link that contains text and not by the href attribute, you can use

Driver.Instance.FindElement(By.XPath("//a[contains(text(), 'long')]"))



回答2:


I don't think the problem is your selector, I think it's the object you're trying to return the results of FindElements to.

In c#, FindElements returns a ReadOnlyCollection<IWebElement> object, not a List object. If you change your linkList definition, it should work:

ReadOnlyCollection<IWebElement> linkList = Driver.Instance.FindElements(By.TagName("a"));

You may also need to add this using:

using System.Collections.ObjectModel;


来源:https://stackoverflow.com/questions/28572892/selenium-how-to-find-element-by-partial-href

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!