Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Web Scraping ด้วย Python และ Scrapy

Scrapy เป็นเฟรมเวิร์กยอดนิยมสำหรับสร้างเว็บครอลเลอร์/สแครพเปอร์ ใช้ high-level APIs ทำให้ scraping ง่ายและมีประสิทธิภาพ

การติดตั้ง

pip install Scrapy
# หรือถ้ามี Anaconda
conda install -c conda-forge scrapy

รองรับ Python 2 และ 3 หลังติดตั้งจะมีคำสั่ง scrapy ในเทอร์มินัล

เริ่มโปรเจกต์ใหม่

$ scrapy startproject scrapy_example
$ cd scrapy_example
$ scrapy genspider example example.com

โครงสร้างโปรเจกต์

scrapy_example/
├── scrapy.cfg
└── scrapy_example/
    ├── __init__.py
    ├── items.py
    ├── middlewares.py
    ├── pipelines.py
    ├── settings.py
    ├── spiders/
    │   └── __init__.py
    └── __pycache__/

ใช้ Scrapy Shell ทดสอบ

$ scrapy shell "https://www.wsj.com/india"
# จะได้ response object
>>> view(response)  # เปิดในเบราว์เซอร์ดู
>>> response.css(".wsj-headline-link::text").extract_first()
'China Fears Loom Over Stocks After January Surge'
>>> response.css(".wsj-headline-link").extract_first()
'China Fears Loom...'
>>> response.css('a::attr(href)').extract()  # ดึงลิงก์ทั้งหมด
['https://www.google.com/...', 'https://www.wsj.com/...', ...]
>>> response.css(".wsj-comment-count::text").extract()
['71', '59']

CSS Selectors สำคัญ

  • tag: เลือกตามแท็ก HTML
  • .class: เลือกตาม class
  • #id: เลือกตาม id
  • ::text: ดึงข้อความภายใน
  • ::attr(name): ดึง attribute
  • parent > child: ลูกโดยตรง
  • ancestor descendant: ลูกชั้นใน

ขั้นตอนสร้าง Spider จริง

  1. สร้างไฟล์ใน spiders/
  2. กำหนด name, start_urls, parse()
  3. ใช้ response.css() หรือ response.xpath() ดึงข้อมูล
  4. Yield item หรือ dictionary
  5. รันด้วย scrapy crawl spider_name -o output.json

ฟีเจอร์ขั้นสูง

  • Item Pipeline: ทำความสะอาด ตรวจสอบ บันทึกลง DB
  • Middleware: จัดการ request/response (proxy, user-agent, retry)
  • Settings: DOWNLOAD_DELAY, CONCURRENT_REQUESTS, ROBOTSTXT_OBEY
  • ScrapyRT: รันผ่าน REST API

ข้อควรระวัง

  • เคารพ robots.txt และ Terms of Service
  • ตั้ง DOWNLOAD_DELAY ให้เหมาะสม กันแบน IP
  • ใช้ User-Agent จริง Rotate proxies หากต้องการ scale
  • หลีกเลี่ยงการ scrape ข้อมูลส่วนตัว/ลิขสิทธิ์