2014-12-13 97 views
2

如何獲得question第一,下劃線和最後一部分的文本,並將其存儲到一個變量,使用分裂?分裂:獲取XPATH文本塊是不是唯一的要素

見底部的HTML。我想作以下變量具有以下值:

first_part = "Jingle bells, jingle bells, jingle all the" 
second_part = "_______" 
third_part = "! Oh what fun it is to ride in one-horse open sleigh!" 

我去here,使用的XPath

//*[@id="question_container"]/div[1]/span/text()[1] #this is first_part 
//*[@id="question_container"]/div[1]/span/span  #this is second_part 
//*[@id="question_container"]/div[1]/span/text()[2] #this is third_part 

,並將其應用到下面的HTML。他們回到在測試通緝值,但對於我的程序,斯普林特似乎拒絕他們:

first_part = browser.find_by_xpath(xpath = '//*[@id="question_container"]/div[1]/span/text()[1]').text 
second_part = browser.find_by_xpath(xpath = '//*[@id="question_container"]/div[1]/span/span').text 
third_part = browser.find_by_xpath(xpath = '//*[@id="question_container"]/div[1]/span/text()[2]').text 

print first_part 
print second_part 
print third_part 

-------------- OUTPUT  ------------- 

[] 
[] 
[] 

我在做什麼錯了,爲什麼錯了,我應該怎麼更改我的代碼?

的參照的HTML(其輕微地被編輯爲「鈴兒響叮噹」,以更好地傳達該問題),使用分裂的browser.html特徵被檢索:

<div id="question_container" style="display: block;"> 
<div class="question_wrap"> 

<span class="question">Jingle bells, jingle bells, jingle all the 
<span class="underline" style="display: none;">_______</span> 
<input type="text" name="vocab_answer" class="answer" id="vocab_answer"></input> 
! Oh what fun it is to ride in one-horse open sleigh!</span> 

</div></div> 

回答

1

xpath傳遞給find_by_xpath()方法必須指向/結果到元素,而不是文本節點。

一個辦法是找到外span,得到它的html和飼料它lxml.html

from lxml.html import fromstring 

element = browser.find_by_xpath(xpath='//div[@id="question_container"]//span[@class="question"]') 

root = fromstring(element.html) 
first_part = root.xpath('./text()[1]')[0] 
second_part = root.xpath('./span/text()')[0] 
third_part = root.xpath('./text()[last()]')[0] 

print first_part, second_part, third_part 

打印:

Jingle bells, jingle bells, jingle all the 
_______ 
! Oh what fun it is to ride in one-horse open sleigh! 
+0

什麼時候使用,而不是'find_by_xpath()'什麼?我在Splinter的文檔中找不到其他相關方法。 – 2014-12-13 03:11:22

+0

@Princee你應該找到'類=「問題」'第一'span'。然後,你可以得到文本的各個部分,肯定有多個選項。你能提供一個鏈接到我的網站測試?謝謝。 – alecxe 2014-12-13 03:12:22

+0

@Princee感謝,請嘗試在更新後的答案的解決方案。 – alecxe 2014-12-13 03:34:50