実践スクレイピング

Pythonで学ぶWebスクレイピング

Thomas Laetsch

Data Scientist, NYU

DataCamp サイト

Pythonで学ぶWebスクレイピング

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で学ぶWebスクレイピング

course-block を確認

first_div = course_divs[0]

children = first_div.xpath('./*')
print( len(children) ) >>> 3
Pythonで学ぶWebスクレイピング

最初の子要素

first_div = course_divs[0]

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

print( first_child.extract() ) >>> <a class=... />
Pythonで学ぶWebスクレイピング

2番目の子要素

first_div = course_divs[0]

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

print( second_child.extract() ) >>> <div class=... />
Pythonで学ぶWebスクレイピング

忘れられた子要素

first_div = course_divs[0]

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

print( third_child.extract() ) >>> <span class=... />
Pythonで学ぶWebスクレイピング

リスト化

  • 1つのCSSロケーターで
    links = response.css('div.course-block > a::attr(href)').extract()
    
  • 段階的に
# ステップ1: コースブロック
course_divs = response.css('div.course-block')

# ステップ2: ハイパーリンク要素 hrefs = course_divs.xpath('./a/@href')
# ステップ3: リンクを抽出 links = hrefs.extract()
Pythonで学ぶWebスクレイピング

コース一覧を取得

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で学ぶWebスクレイピング

リンク抽出の完了

Pythonで学ぶWebスクレイピング

Preparing Video For Download...