2012-08-23 32 views
0

我正在使用HTMLXPathSelector來解析HTML內容。目標網站有一個隨機的HTML標籤。例如:它的格式可以是:如何在選擇器中選擇子元素

<div class="doctor_ans"> 
    <h3>Title</h3> 
    <p style="text-align: justify;"> 
    <span style="font-size: 12px;"> 
     <span style="font-family: arial,helvetica,sans-serif;"> 
     <font color="#000000">I would like to get contain here.</font> 
     </span> 
    </span> 
    </p>  
</div> 

<div class="doctor_ans"> 
    <h3>Title</h3> 
    <p style="text-align: justify;"> 
    <span style="font-size: 12px;"> 
     <span style="font-family: arial,helvetica,sans-serif;"> 
     I would like to get contain here.> 
     </span> 
    </span> 
    </p>  
</div> 

<div class="doctor_ans"> 
    <h3>Title</h3> 
    <p> 
    <span style="font-size: 12px;"> 
     <span style="font-family: arial,helvetica,sans-serif;"> 
     <font color="#000000">I would like to get contain here.</font> 
     </span> 
    </span> 
    </p>  
</div> 

<div class="doctor_ans"> 
    <h3>Title</h3> 
    <p> 
    <span style="font-size: 12px;"> 
     I would like to get contain here. 
    </span> 
    </p>  
</div> 

等。
請給我你的建議如何解析此內容。 HTML標籤隨機出現。所以,我需要一種方法來獲取子元素來查找最終元素。

+0

問題是?你有什麼嘗試? –

回答

0

我有更多使用Selenium的經驗,但xpath部分應該是一樣的。使用xpath ='。// span'選擇子元素,然後獲取該元素的.text。如果子元素爲空,則放棄下一個元素。

1
hxs = HtmlXPathSelector(response) 
hxs.select('div[@class="doctor_ans"]/p[1]//text()').extract() 

會給你一個doctor_ans div中第一段中單獨一段文字的列表。