2016-10-22 54 views
0

我需要在沒有class或id的嵌套div中查找某個文本。Selenium:使用xpath查找使用特定純文本的嵌套div

這是html的結構。

<div class="active_row"> 
    <div class="outcomes"> 
    <div class="event_outcome" onclick="doSomething"> 
    <div>Target Text</div> 
    </div> 
    </div> 
</div> 

我嘗試直接使用我從here獲得的示例訪問文本。

driver.find_elements_by_xpath("//div[contains(., 'Target Text')]") 

這將返回一個包含目標文本,但是當我運行在其上的點擊方法沒有任何反應元素的列表。

什麼是設置此查詢來查找文本,然後點擊event_outcome類的div的最佳方法是什麼?

回答

2

要選擇與event_outcome類股利,你可以在你的XPath中添加謂詞來檢查類屬性值:

//div[contains(., 'Target Text') and @class='event_outcome'] 

或添加謂詞來檢查onclick屬性的存在:

//div[contains(., 'Target Text') and @onclick] 
+0

謝謝!!!我組合了兩個謂詞,然後打印結果以確認使用'.text'。現在它點擊!謝謝! –

1

設置此查詢來查找文本然後點擊帶有event_outcome類的div的最佳方式是什麼?

你應該嘗試使用下面xpath這將返回<div class="event_outcome" onclick="doSomething">文本Target Text這將fullfil您所有的需求如下: -

element = driver.find_element_by_xpath(".//div[contains(., 'Target Text') and @class='event_outcome']") 
print(element.text) 
element.click() 

或者你也可以得到同樣的與內文本的精確匹配使用normalize-space()函數的xpath如下: -

element = driver.find_element_by_xpath(".//div[normalize-space()='Target Text' and @class='event_outcome']") 
print(element.text) 
element.click() 
+1

大聲笑...謝謝!在看到你的答案之前,做了同樣的事情。添加正常化只是節省了我額外的工作。 –

相關問題