2016-07-29 29 views
2

我試圖使用Python硒火狐的webdriver抓住從這個HTML氫含量「我的數據標題」Python中硒的webdriver - 抓鬥DIV後指定一個

<div class="box"> 
    <ul class="navigation"> 
     <li class="live"> 
      <span> 
       Section Details 
      </span> 
     </li> 
    </ul> 
</div> 

<div class="box"> 
    <h2> 
     My Data Title 
    </h2> 
</div> 

<div class="box"> 
    <ul class="navigation"> 
     <li class="live"> 
      <span> 
       Another Section 
      </span> 
     </li> 
    </ul> 
</div> 

<div class="box"> 
    <h2> 
     Another Title 
    </h2> 
</div> 

每個div有一類的所以我不能輕易識別出我想要的。有沒有一種方法可以告訴Selenium抓住盒子類中的h2,這個盒子裏有一個名爲'Section Details'的部分?

回答

2

如果你想抓住h2在具有跨度文本Section Details一後到來的框類試試下面xpath使用preceding: -

(//h2[preceding::span[normalize-space(text()) = 'Section Details']])[1] 

或使用following

(//span[normalize-space(text()) = 'Section Details']/following::h2)[1] 

Another Section只是改變xpath爲跨度文本: -

(//h2[preceding::span[normalize-space(text()) = 'Another Section']])[1] 

(//span[normalize-space(text()) = 'Another Section']/following::h2)[1] 
1

是的,你需要做一些複雜的XPath查詢:

referenceElementList = driver.find_elements_by_xpath("//span") 
for eachElement in referenceElementList: 
    if eachElement.get_attribute("innerHTML") == 'Section Details': 
     elementYouWant = eachElement.find_element_by_xpath("../../../following-sibling::div/h2") 

elementYouWant.get_attribute("innerHTML") should give you "My Data Title" 

我的代碼如下:

  1. 找到所有span元素,無論他們是在HTML哪裏,並將它們存儲在一個名爲列表referenceElementList;
  2. 逐個遍歷所有span元素referenceElementList,查找innerHTML屬性爲'Section Details'的跨度。
  3. 如果有比賽,我們已經找到了跨度,而我們導航向後三個層次來定位封閉div[@class='box'],並找到該div元素的下一個兄弟,這是第二div元素,
  4. 最後,我們找到來自其父項的h2元素。

你能告訴我,如果我的代碼有效嗎?我可能在反向導航的地方出錯了。

您可能遇到的潛在困難,innerHTML屬性可能包含製表符,新行和空格字符,在這種情況下,您需要先使用regex進行一些過濾。

2

這就是一個XPath選擇標題文本「組詳細信息」下面:

//div[@class='box'][normalize-space(.)='Section Details']/following::h2 
+0

可以請你告訴我更多關於這個'正常化空間'(。)? –

+0

@Yu Zhang,它刪除空格(換行,換行...)並用一個空格替換任何雙空格。 –

+0

非常感謝你,upvoted教我新的東西。 –