Скрапінг на практиці

Вебскрапінг у Python

Thomas Laetsch

Data Scientist, NYU

Сайт DataCamp

Вебскрапінг у Python

Що там у div?

# response loaded with HTML from https://www.datacamp.com/courses/all
course_divs = response.css('div.course-block')
print( len(course_divs) )
>>> 185
Вебскрапінг у Python

Оглядаємо course-block

first_div = course_divs[0]

children = first_div.xpath('./*')
print( len(children) ) >>> 3
Вебскрапінг у Python

Перший нащадок

first_div = course_divs[0]

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

print( first_child.extract() ) >>> <a class=... />
Вебскрапінг у Python

Другий нащадок

first_div = course_divs[0]

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

print( second_child.extract() ) >>> <div class=... />
Вебскрапінг у Python

Третій, забутий

first_div = course_divs[0]

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

print( third_child.extract() ) >>> <span class=... />
Вебскрапінг у Python

Усе про списки

  • В одному CSS-локаторі
    links = response.css('div.course-block > a::attr(href)').extract()
    
  • Крок за кроком
# step 1: course blocks
course_divs = response.css('div.course-block')

# step 2: hyperlink elements hrefs = course_divs.xpath('./a/@href')
# step 3: extract the links links = hrefs.extract()
Вебскрапінг у Python

Навчальні посилання

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
...
Вебскрапінг у Python

Посилання отримано

Вебскрапінг у Python

Preparing Video For Download...