2017-08-31 76 views
1

我想獲得「tracked_by」id到「buzz_off」id之間的電影名稱。我已經創建了一個可以在「tracked_by」id之後抓取名字的選擇器。但是,我的意圖是讓腳本進行解析,直到找到「buzz_off」標識。元件在其內的名稱是:任何與CSS選擇器中的「until」相似的東西?

html = ''' 
<div class="list"> 
    <a id="allow" name="allow"></a> 
<h4 class="cluster">Allow</h4> 
<div class="base min"><a href="...">Sally</a></div> 
<div class="base max"><a href="..">Blood Diamond</a></div> 
    <a id="tracked_by" name="tracked_by"></a> 
<h4 class="cluster">Tracked by</h4> 
<div class="base min"><a href="..">Gladiator</a></div> 
<div class="base max"><a href="..">Troy</a></div> 
    <a id="buzz_off" name="buzz_off"></a> 
<h4 class="cluster">Buzz-off</h4> 
<div class="base min"><a href="..">Heat</a></div> 
<div class="base max"><a href="..">Matrix</a></div> 
</div> 
''' 

from lxml import html as htm 
root = htm.fromstring(html) 
for item in root.cssselect("a#tracked_by ~ div.base a"): 
    print(item.text) 

我已經與(在上述腳本中也提到)嘗試選擇器:

a#tracked_by ~ div.base a 

結果我有:

Gladiator 
Troy 
Heat 
Matrix 

結果我想得到:

Gladiator 
Troy 

順便說一句,我想解析名稱使用這個選擇器不風格。

+0

[無法使用選擇器。](https://stackoverflow.com/questions/13330757/how-can-i-target-a-specific-group-of-siblings-in-a-flat-hierarchy/13330785#13330785)你需要額外的代碼。 – BoltClock

回答

0

this是css選擇器的參考。正如你所看到的,它沒有任何形式的邏輯,因爲它不是一種編程語言。你必須在python中使用while not循環,並且每次處理一個元素,或者將它們追加到列表中。

+1

感謝您的回答,Treehee。如果是這種情況,那麼我不需要借用python的任何邏輯來處理它;相反,我會很容易地使用這個表達式「//div[./preceding-sibling::h4[1]='Tracking by'] // text()」來使用xpath,它能夠很好地滿足目的。因爲在大多數情況下我更喜歡css選擇器,所以我想從中學習它的限制。謝謝。 – SIM

相關問題