2016-05-03 64 views
3

這是我的HTML:如何返回XPath表達式的單個字符串值?

<?xml version="1.0" encoding="UTF-8"?> 

<div class="single-main"> 
    <h3 class="description-area">Description</h3> 
    <p>bla bla bla 
    <br/> some text 
    <br/> some text here , 
    <br/> other text here 
    </p> 
</div> 

我想要得到的全部文本,但在一個 XPath表達式。

這是我的代碼:

response.xpath(".//h3[@class='description-area']/following-sibling::p 
       //text()[count(preceding-sibling::br) >= 0]").extract()[0] 

,但它的第br之前只返回文本(我知道爲什麼,那是因爲我使用.extract()[0],如果我使用.extract()[1] [2] ....我會得到我想要的,但我必須使用.extract [0],因爲它是一個平臺,這樣做。是否有任何XPath返回整個文本,但在一個字符串,而不是多個字符串?

回答

3

string(/)將返回整個文檔的字符串值。


更新:要在string()同樣返回由這個XPath返回的四個分開的字符串,

.//h3[@class='description-area']/following-sibling::p//text()[count(preceding-sibling::br) >= 0] 

作爲單個字符串,包裹上述的XPath:

string(.//h3[@class='description-area']/following-sibling::p//text()[count(preceding-sibling::br) >= 0]) 

更新2:但brtext()演習是沒有必要的。你可以簡單地得到p的字符串值:

string(.//h3[@class='description-area']/following-sibling::p) 
+1

你意味着使用這個請'.// H3 [@類=「描述區域」] /以下同胞:: P //字符串( )' –

相關問題