เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

คำอธิบายคอร์สบน DataCamp

เช่นเดียวกับแบบฝึกหัดก่อนหน้า โค้ดในส่วนนี้ค่อนข้างยาวเพราะกำลังทำงานกับ spider สำหรับการ crawl เว็บทั้งหมด แต่อย่าให้ปริมาณโค้ดทำให้หนักใจ ตอนนี้เข้าใจการทำงานของ spider แล้ว และสามารถทำภารกิจง่าย ๆ นี้ได้อย่างแน่นอน!

เช่นเดิม มีฟังก์ชัน previewCourses ไว้ให้ดูตัวอย่างผลลัพธ์ของ spider แต่จะสำรวจ dictionary dc_dict โดยตรงหลังรันโค้ดก็ได้เช่นกัน

ในแบบฝึกหัดนี้ ให้สร้าง CSS Locator string ที่นำไปยังข้อความของคำอธิบายคอร์ส สิ่งที่ต้องรู้คือ ในหน้าคอร์ส ข้อความคำอธิบายคอร์สอยู่ภายใน element p ที่มี class ชื่อ course__description (ขีดล่างสองตัว)

แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร

Web Scraping ด้วย Python

ดูคอร์ส

คำแนะนำการฝึกหัด

  • เติมช่องว่างในเมธอด parse_pages ด้วย CSS Locator string ที่นำไปยังข้อความภายใน element p ซึ่งมี class ชื่อ course__description

หมายเหตุ: หากกด รันโค้ด แล้ว ต้องกด รีเซ็ตเป็นโค้ดตัวอย่าง ก่อนจึงจะสามารถกด รันโค้ด ได้อีกครั้ง!

แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ

ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์

# Import scrapy
import scrapy

# Import the CrawlerProcess: for running the spider
from scrapy.crawler import CrawlerProcess

# Create the Spider class
class DC_Description_Spider(scrapy.Spider):
  name = "dc_chapter_spider"
  # start_requests method
  def start_requests(self):
    yield scrapy.Request(url = url_short,
                         callback = self.parse_front)
  # First parsing method
  def parse_front(self, response):
    course_blocks = response.css('div.course-block')
    course_links = course_blocks.xpath('./a/@href')
    links_to_follow = course_links.extract()
    for url in links_to_follow:
      yield response.follow(url = url,
                            callback = self.parse_pages)
  # Second parsing method
  def parse_pages(self, response):
    # Create a SelectorList of the course titles text
    crs_title = response.xpath('//h1[contains(@class,"title")]/text()')
    # Extract the text and strip it clean
    crs_title_ext = crs_title.extract_first().strip()
    # Create a SelectorList of course descriptions text
    crs_descr = response.css( ____ )
    # Extract the text and strip it clean
    crs_descr_ext = crs_descr.extract_first().strip()
    # Fill in the dictionary
    dc_dict[crs_title_ext] = crs_descr_ext

# Initialize the dictionary **outside** of the Spider class
dc_dict = dict()

# Run the Spider
process = CrawlerProcess()
process.crawl(DC_Description_Spider)
process.start()

# Print a preview of courses
previewCourses(dc_dict)
แก้ไขและรันโค้ด