Scrapen in het echt

Webscraping in Python

Thomas Laetsch

Data Scientist, NYU

DataCamp-site

Webscraping in Python

Wat is die div?

# response geladen met HTML van https://www.datacamp.com/courses/all
course_divs = response.css('div.course-block')
print( len(course_divs) )
>>> 185
Webscraping in Python

course-block inspecteren

first_div = course_divs[0]

children = first_div.xpath('./*')
print( len(children) ) >>> 3
Webscraping in Python

Het eerste kind

first_div = course_divs[0]

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

print( first_child.extract() ) >>> <a class=... />
Webscraping in Python

Het tweede kind

first_div = course_divs[0]

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

print( second_child.extract() ) >>> <div class=... />
Webscraping in Python

Het vergeten kind

first_div = course_divs[0]

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

print( third_child.extract() ) >>> <span class=... />
Webscraping in Python

Lijstjeslief

  • In één CSS-locator
    links = response.css('div.course-block > a::attr(href)').extract()
    
  • Stapsgewijs
# stap 1: course-blocks
course_divs = response.css('div.course-block')

# stap 2: hyperlink-elementen hrefs = course_divs.xpath('./a/@href')
# stap 3: links extraheren links = hrefs.extract()
Webscraping in Python

Naar school gaan

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
...
Webscraping in Python

Links verzameld

Webscraping in Python

Preparing Video For Download...