2016-11-27 119 views
0

首先,我很抱歉,如果標題還不是很清楚的信息;我不太清楚如何解釋我想用標題做什麼;無論如何。的Python的XPath - 得到正確的順序

我碰到一個網站上的一些信息;我已經有我想要的信息,但是當我運行該腳本,我得到的輸出如下:

Ivern Jungle 
Starting Items             
Hunter's Talisman 
Refillable Potion 
Warding Totem 
First Goal              


Stalker's Blade 
Tracker's Knife 
Boots of Speed 
Hunter's Potion 
Vision Ward 
Sweeping Lens 
Second Goal 

當我想它是這樣的:

Ivern Jungle 

Starting Items             
Hunter's Talisman 
Refillable Potion 
Warding Totem 


First Goal        
Stalker's Blade 
Tracker's Knife 
Boots of Speed 
Hunter's Potion 
Vision Ward 
Sweeping Lens 
Second Goal 

我已經嘗試了一些東西與代碼;這是我能夠按照自己的意願完成工作的唯一途徑。 Ivern jungle是一個標題; Starting Items是另一個標題,First Goal是另一個標題;在我首先獲得標題和其他信息(項目)之前。這是我現在的代碼。

 for build_names in guide_page.xpath(".//div[@class='build-container box-shadow-lb']" 
              "/div[1]/div[1]/div[1]/div[1]/div[1]"): 

      for title in build_names.xpath("div[1]/h2/text() | div[3]/div[1]/div/h2/text() | " 
              "div[3]/div[1]/div/div/div/a/div[2]/span/text()"): 
       print(title) 

我越來越從title大部分的信息循環,因爲這就是我設法得到它的權利;如果有更有效的方式去做;請讓我知道

順便說,信息是從一個特定的網站,但網站可以改變從另一個特定網站,我得到這樣的信息:

Kled The Talker # Title 
Kled Tank/Ad Top # Title            
Mercury's Treads 
The Black Cleaver 
Titanic Hydra 
Frozen Mallet 
Dead Man's Plate 
Guardian Angel 
Kled Ad/LifeSteal # Title            
Mercury's Treads 
The Black Cleaver 
Ravenous Hydra 
Death's Dance 
Maw of Malmortius 
Guardian Angel 

正如你可以看到我不明白之間的任何空間;如果您轉到first website,您可以看到,在項目部分中,項目部分中每個標題的右側都有註釋;我認爲那些將空格放在輸出中的是因爲second website中沒有註釋。那麼,這是我的主要問題;我怎樣才能格式化輸出?如果我沒有解釋得太清楚,請讓我知道,我會更新問題,謝謝! :)

回答

1

您可以通過使用類往往屬性瀏覽樹相當容易一點。這樣一來,你可以重寫你的腳本是這樣的:

for div in page.xpath('//div[contains(@class, "item-wrap")]'): 
    print("\n{bar}\n{title}\n{bar}".format(
     bar="#"*20, 
     title=div.xpath('.//h2/text()')[0].strip())) 
    print('\n'.join(x.strip() for x in div.xpath(
     './/div[contains(@class, "main-items")]//span/text()'))) 

輸出摘錄:

#################### 
Starting Items 
#################### 
Hunter's Talisman 
Refillable Potion 
Warding Totem 

#################### 
First Goal 
#################### 
Stalker's Blade 
Tracker's Knife 
Boots of Speed 
Hunter's Potion 
Vision Ward 
Sweeping Lens 

#################### 
Second Goal 
#################### 
Rod of Ages 
Boots of Mobility 
Ionian Boots of Lucidity 
Boots of Swiftness 
Sorcerer's Shoes 
Oracle Alteration 

這些XPath的效果一樣好,你鏈接到第二頁上。

+0

非常好,非常感謝。如果問得不多,在我正在使用的'for'之上,我有點'_ if',它只顯示一段代碼。在html中,有時候''div''有'style =「display:block;'或'style =」display:none;'我只想使用'style =「display:block;',主要的; if你看[這裏](http://www.mobafire.com/league-of-legends/build/open-your-eyes-lee-sin-jungle-guide-393845)你可以看到上面有兩張圖片標題爲「建立1」和「建立2」;我只是想從「建立1」的信息如何能做到這一點感謝 – Aguxez

+1

@fuhrerguxez這並不容易:這些屬性通過jQuery的動態添加但是,如果?。 「Build 1」總是在HTML中的「Build 2」之前列出,然後你可以用'page.xpath('// div [contains(@class,「build-container」 。)]/DIV')[0]'你應該從該節點然後重訂任何後續的XPath –

+0

好吧,我得到它的工作。我改變了一些東西,我不能將它粘貼爲評論,因爲這會花費很大的空間我想,我會徹底地測試它,謝謝你的幫助! – Aguxez