Spider แบบ Class

Web Scraping ด้วย Python

Thomas Laetsch

Data Scientist, NYU

Spider ของคุณ

import scrapy
from scrapy.crawler import CrawlerProcess

class SpiderClassName(scrapy.Spider):
    name = "spider_name"
    # the code for your spider
    ...

process = CrawlerProcess()

process.crawl(SpiderClassName)

process.start()
Web Scraping ด้วย Python

Spider ของคุณ

  • การ import ที่จำเป็น
import scrapy
from scrapy.crawler import CrawlerProcess
  • ส่วนที่จะโฟกัส: ตัว spider
class SpiderClassName(scrapy.Spider):
    name = "spider_name"
    # the code for your spider
    ...
  • การรัน spider
# initiate a CrawlerProcess
process = CrawlerProcess()

# tell the process which spider to use
process.crawl(YourSpider)

# start the crawling process
process.start()
Web Scraping ด้วย Python

สร้าง Spider ดักข้อมูล

class DCspider( scrapy.Spider ):

    name = 'dc_spider'

    def start_requests( self ):
        urls = [ 'https://www.datacamp.com/courses/all' ]
        for url in urls:
            yield scrapy.Request( url = url, callback = self.parse )

    def parse( self, response ):
        # simple example: write out the html
        html_file = 'DC_courses.html'
        with open( html_file, 'wb' ) as fout:
            fout.write( response.body )
  • ต้องมีฟังก์ชันชื่อ start_requests
  • ต้องมีฟังก์ชัน parser อย่างน้อยหนึ่งตัวสำหรับจัดการโค้ด HTML
Web Scraping ด้วย Python

มาสร้าง Spider ไปด้วยกัน

Web Scraping ด้วย Python

Preparing Video For Download...