Introducere în Selector-ul scrapy

Web Scraping în Python

Thomas Laetsch

Data Scientist, NYU

Configurarea unui Selector

from scrapy import Selector
html = '''
<html>
  <body>
    <div class="hello datacamp">
      <p>Hello World!</p>
    </div>
    <p>Enjoy DataCamp!</p>
  </body>
</html>
'''
sel = Selector( text = html )
  • S-a creat un obiect Selector scrapy dintr-un șir cu codul html

  • Selector-ul sel a selectat întregul document html

Web Scraping în Python

Selectarea Selector-elor

  • Putem folosi apelul xpath în cadrul unui Selector pentru a crea noi Selector-e pentru fragmente specifice din codul html

  • Rezultatul este un SelectorList de obiecte Selector

sel.xpath("//p")

# outputs the SelectorList: [<Selector xpath='//p' data='<p>Hello World!</p>'>, <Selector xpath='//p' data='<p>Enjoy DataCamp!</p>'>]
Web Scraping în Python

Extragerea datelor dintr-un SelectorList

  • Utilizați metoda extract()
>>> sel.xpath("//p")

out: [<Selector xpath='//p' data='<p>Hello World!</p>'>, <Selector xpath='//p' data='<p>Enjoy DataCamp!</p>'>]
>>> sel.xpath("//p").extract()

out: [ '<p>Hello World!</p>', '<p>Enjoy DataCamp!</p>' ]
  • Se poate folosi extract_first() pentru a obține primul element din listă
>>> sel.xpath("//p").extract_first()

out: '<p>Hello World!</p>'
Web Scraping în Python

Extragerea datelor dintr-un Selector

ps = sel.xpath('//p')

second_p = ps[1]
second_p.extract()

out: '<p>Enjoy DataCamp!</p>'
Web Scraping în Python

Selectați acest curs!

Web Scraping în Python

Preparing Video For Download...