2013-08-17 43 views
26

我想在<h5>中找到此链接的元素“us states”。我正在Craigslist中尝试这个。任何帮助将高度赞赏需要在CSS中查找硒中的元素

这里是网址:http://auburn.craigslist.org/

<html class=""> 
<head> 
<body class="homepage w1024 list"> 
    <script type="text/javascript"> 
    <article id="pagecontainer"> 
      <section class="body"> 
     <table id="container" cellspacing="0" cellpadding="0" 
    <tbody> 
      <tr> 
    <td id="leftbar"> 
    <td id="center"> 
    <td id="rightbar"> 
     <ul class="menu collapsible"> 
      <li class="expand s"> 
      <li class="s"> 
      <li class="s"> 
       <h5 class="ban hot">us states</h5> 
       <ul class="acitem" style="display: none;"> 
      </li> 
     <li class="s"> 
     <li class="s"> 

回答

62

只有在你的情况下使用类名是不够的。

  • By.cssSelector(".ban")有15级匹配的节点
  • By.cssSelector(".hot")有11级匹配的节点
  • By.cssSelector(".ban.hot")有5级匹配的节点

因此,你需要更多的限制,将它缩小。 下面的选项1和2可用于css选择器,1可能是最适合您需求的选项。

选项1:使用列表项人指数(CssSelector或XPath)

限制

  • 不够稳定,如果网站的结构变化

例子:

driver.FindElement(By.CssSelector("#rightbar > .menu > li:nth-of-type(3) > h5")); 
driver.FindElement(By.XPath("//*[@id='rightbar']/ul/li[3]/h5")); 

选项2:使用硒的FindElements,然后索引它们。(CssSelector或XPath)

限制

  • 不够稳定,如果网站的结构变化
  • 没有原生选择的方式

例子:

// note that By.CssSelector(".ban.hot") and //*[contains(@class, 'ban hot')] are different, but doesn't matter in your case 
IList<IWebElement> hotBanners = driver.FindElements(By.CssSelector(".ban.hot")); 
IWebElement banUsStates = hotBanners[3]; 

选项3:使用文本(只的XPath)

限制

  • 不为多语言网站
  • 只有XPath的,而不是为Selenium的CssSelector

例子:

driver.FindElement(By.XPath("//h5[contains(@class, 'ban hot') and text() = 'us states']")); 

方案4:指数分组选择器(仅支持XPath)

限制

  • 若网站的结构变化仅适用于XPath的
  • ,不CssSelector
足够稳定

例如:

driver.FindElement(By.XPath("(//h5[contains(@class, 'ban hot')])[3]")); 

方案5:找到隐藏列表项的HREF链接,然后遍历回H5(只的XPath)

限制

  • 只有XPath的,不CssSelector
  • 低性能
  • Tricky XP ATH

例子:

driver.FindElement(By.XPath(".//li[.//ul/li/a[contains(@href, 'geo.craigslist.org/iso/us/al')]]/h5")); 
+1

By.cssSelector(“.ban.hot:nth-of-type(3)”) – 2015-05-18 12:02:49

+0

这是Yi Zengs答案的补充。出于某种原因,他没有提到你可以在cssSelector中使用nth-of-type类名。您不必通过元素列表来获取包含类名称的第N个元素 – 2015-05-21 13:36:13

+0

@Vlad:感谢您指出。 'n-type-type'是CSS3,Selenium当时并没有完全支持所有浏览器。它现在可能受到支持,但我没有机会验证。你用最新的Selenium测试过它吗? –

0

By.cssSelector(".ban")By.cssSelector(".hot")By.cssSelector(".ban.hot")都应该选择它,除非是具有这些类的另一个因素。

在CSS中,.name表示找到一个与name类有关的元素。 .foo.bar.baz表示查找具有所有这些类的元素(在同一元素中)。

但是,这些选择器中的每一个将只选择与页面上匹配的第一个元素。如果您需要更具体的内容,请发布其他具有这些类的元素的HTML。

+0

感激你们! – ktmrocks

0

你可以描述你的CSS选择喜欢的层叠样式表DOWS:

protected override void When() 
{ 
    SUT.Browser.FindElements(By.CssSelector("#carousel > a.tiny.button")) 
}