DataCamp विवरण
पिछले अभ्यास की तरह, यहाँ का कोड भी लंबा है क्योंकि आप एक पूरे वेब-क्रॉलिंग spider के साथ काम कर रहे हैं! लेकिन फिर से, कोड की मात्रा से घबराइए नहीं. अब आपको spiders कैसे काम करते हैं, इस पर पकड़ है, और आप यहाँ दिए गए आसान कार्य को पूरी तरह कर सकते हैं!
पिछले अभ्यास की तरह, हमने एक फंक्शन previewCourses बनाया है जो आपको spider का आउटपुट प्रीव्यू करने देता है, लेकिन आप कोड चलाने के बाद dc_dict डिक्शनरी को सीधे भी देख-परख सकते हैं.
इस अभ्यास में, आपसे कहा गया है कि आप एक CSS Locator string बनाएँ जो सीधे कोर्स विवरण के टेक्स्ट तक पहुँचे. आपको बस इतना जानना है कि कोर्स पेज पर, कोर्स विवरण का टेक्स्ट एक पैराग्राफ p एलिमेंट में है, जो course__description (दो अंडरस्कोर) नाम की class से सम्बन्धित है.
यह अभ्यास पाठ्यक्रम का हिस्सा है
Python में Web Scraping
अभ्यास निर्देश
- नीचे
parse_pagesमेथड में दिए गए एक रिक्त स्थान को एक ऐसी CSS Locator string से भरें जो उस पैराग्राफpएलिमेंट के भीतर के टेक्स्ट तक निर्देशित हो, जोcourse__descriptionclass से सम्बन्धित है.
NOTE: यदि आप कोड चलाने के लिए Run Code दबाते हैं, तो फिर से सफलतापूर्वक Run Code का उपयोग करने के लिए आपको Reset to Sample Code अवश्य करना होगा!!
इंटरैक्टिव व्यावहारिक अभ्यास
इस अभ्यास को इस नमूना कोड को पूरा करके आज़माएँ।
# 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)