Scraper pour de vrai

Web Scraping en Python

Thomas Laetsch

Data Scientist, NYU

Site DataCamp

Web Scraping en Python

C’est quoi ce div ?

# response chargé avec le HTML depuis https://www.datacamp.com/courses/all
course_divs = response.css('div.course-block')
print( len(course_divs) )
>>> 185
Web Scraping en Python

Inspection de course-block

first_div = course_divs[0]

children = first_div.xpath('./*')
print( len(children) ) >>> 3
Web Scraping en Python

Le premier enfant

first_div = course_divs[0]

children = first_div.xpath('./*')
first_child = children[0]

print( first_child.extract() ) >>> <a class=... />
Web Scraping en Python

Le deuxième enfant

first_div = course_divs[0]

children = first_div.xpath('./*')
second_child = children[1]

print( second_child.extract() ) >>> <div class=... />
Web Scraping en Python

L’oublié

first_div = course_divs[0]

children = first_div.xpath('./*')
third_child = children[2]

print( third_child.extract() ) >>> <span class=... />
Web Scraping en Python

Listes à gogo

  • En un sélecteur CSS
    links = response.css('div.course-block > a::attr(href)').extract()
    
  • Par étapes
# étape 1 : blocs de cours
course_divs = response.css('div.course-block')

# étape 2 : éléments lien hrefs = course_divs.xpath('./a/@href')
# étape 3 : extraire les liens links = hrefs.extract()
Web Scraping en Python

Retour à l’école

for l in links:
    print( l )

>>> /courses/free-introduction-to-r
>>> /courses/data-table-data-manipulation-r-tutorial
>>> /courses/dplyr-data-manipulation-r-tutorial
>>> /courses/ggvis-data-visualization-r-tutorial
>>> /courses/reporting-with-r-markdown
>>> /courses/intermediate-r
...
Web Scraping en Python

Liens obtenus

Web Scraping en Python

Preparing Video For Download...