2013-08-17 45 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")) 
}