Mô tả DataCamp
Tương tự bài tập trước, đoạn mã ở đây khá dài vì bạn đang làm việc với một spider thu thập dữ liệu web hoàn chỉnh! Nhưng đừng để lượng mã làm bạn chùn bước — bạn đã nắm được cách spider hoạt động và hoàn toàn có thể hoàn thành nhiệm vụ đơn giản dưới đây!
Như ở bài trước, chúng tôi đã tạo hàm previewCourses để bạn xem trước đầu ra của spider, nhưng sau khi chạy mã bạn cũng có thể tự do khám phá dictionary dc_dict nữa.
Trong bài này, bạn cần tạo một chuỗi CSS Locator trỏ trực tiếp tới phần văn bản mô tả khóa học. Tất cả những gì bạn cần biết là: ở trang khóa học, văn bản mô tả nằm trong phần tử đoạn văn p thuộc class course__description (hai dấu gạch dưới).
Bài tập này là một phần của khóa học
Web Scraping với Python
Hướng dẫn bài tập
- Điền vào chỗ trống bên dưới trong phương thức
parse_pagesbằng một chuỗi CSS Locator trỏ tới phần văn bản bên trong phần tử đoạn vănpthuộc classcourse__description.
LƯU Ý: Nếu bạn nhấn Chạy mã, bạn phải Đặt lại về mã mẫu thì mới có thể Chạy mã lại thành công!!
Bài tập tương tác thực hành trực tiếp
Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.
# 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)