Python में Web Scraping
Thomas Laetsch
Data Scientist, NYU
import scrapy
from scrapy.crawler import CrawlerProcess
class DC_Chapter_Spider(scrapy.Spider):
name = "dc_chapter_spider"
def start_requests( self ):
url = 'https://www.datacamp.com/courses/all'
yield scrapy.Request( url = url,
callback = self.parse_front )
def parse_front( self, response ):
## फ्रंट कोर्स पेज को पार्स करने का कोड
def parse_pages( self, response ):
## कोर्स पेजों को पार्स करने का कोड
## यहाँ dc_dict भरें
dc_dict = dict()
process = CrawlerProcess()
process.crawl(DC_Chapter_Spider)
process.start()
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 )
def parse_pages( self, response ):# कोर्स टाइटल टेक्स्ट तक जाएँ crs_title = response.xpath('//h1[contains(@class,"title")]/text()')# कोर्स टाइटल टेक्स्ट निकालें और साफ करें crs_title_ext = crs_title.extract_first().strip()# चैप्टर टाइटल्स टेक्स्ट तक जाएँ ch_titles = response.css( 'h4.chapter__title::text' )# चैप्टर टाइटल्स टेक्स्ट निकालें और साफ करें ch_titles_ext = [t.strip() for t in ch_titles.extract()]# इसे हमारी डिक्शनरी में स्टोर करें dc_dict[ crs_title_ext ] = ch_titles_ext
Python में Web Scraping