实战爬取

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 爬取

第二个子元素

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 爬取

列表化

  • 使用一个 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...