2017-08-30 2 views
2

J'essaie de gratter this site en utilisant scrapy. La structure de la page ressemble à ceci:comment sélectionner et extraire des textes entre deux éléments?

<div class="list"> 
    <a id="follows" name="follows"></a> 
<h4 class="li_group">Follows</h4> 
<div class="soda odd"><a href="...">Star Trek</a></div> 
<div class="soda even"><a href="...</a></div> 
<div class="soda odd"><a href="..">Star Trek: The Motion Picture</a></div> 
<div class="soda even"><a href="..">Star Trek II: The Wrath of Khan</a></div> 
<div class="soda odd"><a href="..">Star Trek III: The Search for Spock</a></div> 
<div class="soda even"><a href="..">Star Trek IV: The Voyage Home</a></div> 
    <a id="followed_by" name="followed_by"></a> 
<h4 class="li_group">Followed by</h4> 
<div class="soda odd"><a href="..">Star Trek V: The Final Frontier</a></div> 
<div class="soda even"><a href="..">Star Trek VI: The Undiscovered Country</a></div> 
<div class="soda odd"><a href="..">Star Trek: Deep Space Nine</a></div> 
<div class="soda even"><a href="..">Star Trek: Generations</a></div> 
<div class="soda odd"><a href="..">Star Trek: Voyager</a></div> 
<div class="soda even"><a href="..">First Contact</a></div> 
    <a id="spin_off" name="spin_off"></a> 
<h4 class="li_group">Spin-off</h4> 
<div class="soda odd"><a href="..">Star Trek: The Next Generation - The Transinium Challenge</a></div> 
<div class="soda even"><a href="..">A Night with Troi</a></div> 
<div class="soda odd"><a href="..">Star Trek: Deep Space Nine</a></div 
</div> 

Je veux sélectionner et extraire les textes entre: <h4 class="li_group">Follows</h4> et <h4 class="li_group">Followed by</h4> puis textes entre <h4 class="li_group">Followed by</h4> et <h4 class="li_group">Spin-off</h4>
j'ai essayé ce code:

def parse(self, response): 
    for sel in response.css("div.list"): 
     item = ImdbcoItem() 
     item['Follows'] = sel.css("a#follows+h4.li_group ~ div a::text").extract(), 
     item['Followed_by'] = sel.css("a#vfollowed_by+h4.li_group ~ div a::text").extract(), 
     item['Spin_off'] = sel.css("a#spin_off+h4.li_group ~ div a::text").extract(), 
    return item 

Mais la premier élément extrait tous divs non seulement divs entre <h4 class="li_group">Follows</h4> et <h4 class="li_group">Followed by</h4>
Toute aide serait vraiment Helpfu l !!

+0

juste cas, il aide, imdb.com a un (non) API officielle où? vous pouvez obtenir toutes ces données propres, si je me souviens bien. – Neil

Répondre

2

Un motif d'extraction J'aime utiliser pour ces cas est:

    boucle
  • sur les "limites" (ici, h4 éléments)
  • tout en les énumérant à partir de 1
  • en utilisant l'axe following-sibling de XPath, comme dans la réponse de @ Andersson, pour obtenir des éléments avant la prochaine limite,
  • et les filtrer en comptant le nombre des précédents éléments « limites », puisque nous savons de notre énumération où nous sommes

Ce serait la boucle:

$ scrapy shell 'http://www.imdb.com/title/tt0092455/trivia?tab=mc&ref_=tt_trv_cnn' 
(...) 
>>> for cnt, h4 in enumerate(response.css('div.list > h4.li_group'), start=1): 
...  print(cnt, h4.xpath('normalize-space()').get()) 
... 
1 Follows  
2 Followed by  
3 Edited into  
4 Spun-off from  
5 Spin-off  
6 Referenced in  
7 Featured in  
8 Spoofed in  

Et ceci est un exemple d'utilisation l'énumération pour obtenir des éléments entre les limites (notez que cette variable utilisation XPath avec $cnt dans l'expression et le passage cnt=cnt dans .xpath()):

>>> for cnt, h4 in enumerate(response.css('div.list > h4.li_group'), start=1): 
...  print(cnt, h4.xpath('normalize-space()').get()) 
...  print(h4.xpath('following-sibling::div[count(preceding-sibling::h4)=$cnt]', 
         cnt=cnt).xpath(
          'string(.//a)').getall()) 
... 
1 Follows  
['Star Trek', 'Star Trek: The Animated Series', 'Star Trek: The Motion Picture', 'Star Trek II: The Wrath of Khan', 'Star Trek III: The Search for Spock', 'Star Trek IV: The Voyage Home'] 
2 Followed by  
['Star Trek V: The Final Frontier', 'Star Trek VI: The Undiscovered Country', 'Star Trek: Deep Space Nine', 'Star Trek: Generations', 'Star Trek: Voyager', 'First Contact', 'Star Trek: Insurrection', 'Star Trek: Enterprise', 'Star Trek: Nemesis', 'Star Trek', 'Star Trek Into Darkness', 'Star Trek Beyond', 'Star Trek: Discovery', 'Untitled Star Trek Sequel'] 
3 Edited into  
['Reading Rainbow: The Bionic Bunny Show', 'The Unauthorized Hagiography of Vincent Price'] 
4 Spun-off from  
['Star Trek'] 
5 Spin-off  
['Star Trek: The Next Generation - The Transinium Challenge', 'A Night with Troi', 'Star Trek: Deep Space Nine', "Star Trek: The Next Generation - Future's Past", 'Star Trek: The Next Generation - A Final Unity', 'Star Trek: The Next Generation: Interactive VCR Board Game - A Klingon Challenge', 'Star Trek: Borg', 'Star Trek: Klingon', 'Star Trek: The Experience - The Klingon Encounter'] 
6 Referenced in  
(...) 

Voilà comment vous pouvez l'utiliser pour alimenter et élément (ici, je me sers d'un simple dict juste pour illustration):

>>> item = {} 
>>> for cnt, h4 in enumerate(response.css('div.list > h4.li_group'), start=1): 
...  key = h4.xpath('normalize-space()').get().strip() # there are some non-breaking spaces 
...  if key in ['Follows', 'Followed by', 'Spin-off']: 
...   values = h4.xpath('following-sibling::div[count(preceding-sibling::h4)=$cnt]', 
...      cnt=cnt).xpath(
...       'string(.//a)').getall() 
...   item[key] = values 
... 

>>> from pprint import pprint 
>>> pprint(item) 
{'Followed by': ['Star Trek V: The Final Frontier', 
       'Star Trek VI: The Undiscovered Country', 
       'Star Trek: Deep Space Nine', 
       'Star Trek: Generations', 
       'Star Trek: Voyager', 
       'First Contact', 
       'Star Trek: Insurrection', 
       'Star Trek: Enterprise', 
       'Star Trek: Nemesis', 
       'Star Trek', 
       'Star Trek Into Darkness', 
       'Star Trek Beyond', 
       'Star Trek: Discovery', 
       'Untitled Star Trek Sequel'], 
'Follows': ['Star Trek', 
      'Star Trek: The Animated Series', 
      'Star Trek: The Motion Picture', 
      'Star Trek II: The Wrath of Khan', 
      'Star Trek III: The Search for Spock', 
      'Star Trek IV: The Voyage Home'], 
'Spin-off': ['Star Trek: The Next Generation - The Transinium Challenge', 
       'A Night with Troi', 
       'Star Trek: Deep Space Nine', 
       "Star Trek: The Next Generation - Future's Past", 
       'Star Trek: The Next Generation - A Final Unity', 
       'Star Trek: The Next Generation: Interactive VCR Board Game - A ' 
       'Klingon Challenge', 
       'Star Trek: Borg', 
       'Star Trek: Klingon', 
       'Star Trek: The Experience - The Klingon Encounter']} 
>>> 
+0

Merci, fonctionne comme un charme. mais je ne pouvais pas comprendre comment l'utiliser dans mon code. Pouvez-vous s'il vous plaît donner un indice ou me fournir un code à utiliser? – haben

+0

Voir ma réponse modifiée. –

3

Vous pouvez essayer d'utiliser ci-dessous des expressions XPath pour chercher

  • tous les nœuds de texte pour le bloc "suit":

    //div[./preceding-sibling::h4[1]="Follows"]//text() 
    
  • tous les nœuds de texte pour "Suivi par" bloc:

    //div[./preceding-sibling::h4[1]="Followed by"]//text() 
    
  • tous les nœuds de texte pour le bloc "Spin off":

    //div[./preceding-sibling::h4[1]="Spin-off"]//text() 
    
+1

Vous pouvez même simplifier '[./preceding-sibling::h4[1] [. =" Follows "]]' dans '[./preceding-sibling::h4[1] =" Suit "]' –

+0

Oui, c'est logique. Merci – Andersson

+0

Vous êtes juste génial monsieur Andersson. Quelle expression !!! Est-il possible de créer un sélecteur CSS avec les mêmes éléments pour localiser la même chose?Un exemple suffirait. Merci. – SIM