Scraping thực chiến

Web Scraping với Python

Thomas Laetsch

Data Scientist, NYU

Trang DataCamp

Web Scraping với Python

Div là gì?

# response loaded with HTML from https://www.datacamp.com/courses/all
course_divs = response.css('div.course-block')
print( len(course_divs) )
>>> 185
Web Scraping với Python

Khám sát course-block

first_div = course_divs[0]

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

Phần tử con đầu tiên

first_div = course_divs[0]

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

print( first_child.extract() ) >>> <a class=... />
Web Scraping với Python

Phần tử con thứ hai

first_div = course_divs[0]

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

print( second_child.extract() ) >>> <div class=... />
Web Scraping với Python

Phần tử con bị quên

first_div = course_divs[0]

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

print( third_child.extract() ) >>> <span class=... />
Web Scraping với Python

Dùng danh sách

  • Gói gọn bằng một CSS locator
    links = response.css('div.course-block > a::attr(href)').extract()
    
  • Từng bước
# bước 1: khối khóa học
course_divs = response.css('div.course-block')

# bước 2: phần tử liên kết hrefs = course_divs.xpath('./a/@href')
# bước 3: trích xuất liên kết links = hrefs.extract()
Web Scraping với Python

Lấy danh sách khóa học

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 với Python

Đã lấy liên kết

Web Scraping với Python

Preparing Video For Download...