CSS-locators

Webscraping in Python

Thomas Laetsch

Data Scientist, NYU

Rosetta CSStone

  • Vervang / door > (behalve het eerste teken)
    • XPath: /html/body/div
    • CSS-locator: html > body > div
  • Vervang // door een spatie (behalve het eerste teken)
    • XPath: //div/span//p
    • CSS-locator: div > span p
  • Vervang [N] door :nth-of-type(N)
    • XPath: //div/p[2]
    • CSS-locator: div > p:nth-of-type(2)
Webscraping in Python

Rosetta CSStone

XPATH

xpath = '/html/body//div/p[2]'

CSS

css = 'html > body div > p:nth-of-type(2)'
Webscraping in Python

Attributen in CSS

  • Zoek op class met een punt .
    • Voorbeeld: p.class-1 selecteert alle paragrafen met class-1
  • Zoek op id met een hek #
    • Voorbeeld: div#uid selecteert het div-element met id gelijk aan uid
Webscraping in Python

Attributen in CSS

Selecteer paragrafen binnen class class1:

css_locator = 'div#uid > p.class1'

Selecteer alle elementen met class class1:

css_locator = '.class1'
Webscraping in Python

Classstatus

css = '.class1'

Klasseselectie-XPath-alleenclass.png

Webscraping in Python

Classstatus

xpath = '//*[@class="class1"]'

Klasseselectie-XPath-eq.png

Webscraping in Python

Classstatus

xpath = '//*[contains(@class,"class1")]'

Klasseselectie-XPath-contains.png

Webscraping in Python

Selectoren met CSS

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 )
>>> sel.css("div > p")
uit: [<Selector xpath='...' data='<p>Hello World!</p>'>] 

>>> sel.css("div > p").extract()
uit: [ '<p>Hello World!</p>' ]
Webscraping in Python

C(SS) you soon!

Webscraping in Python

Preparing Video For Download...