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

urllib.robotparser: Parse robots.txt ใน Python

urllib.robotparser ช่วยอ่านและตีความ robots.txt เพื่อตรวจสอบว่า bot/crawler ควรเข้าถึง URL ไหนได้บ้าง

robots.txt Format

# robots.txt
Sitemap: https://example.com/sitemap.xml
User-agent: *
Disallow: /admin/
Disallow: /downloads/
Disallow: /media/
Disallow: /static/

RobotFileParser Class

from urllib import robotparser
from urllib.parse import urljoin

AGENT_NAME = 'MyBot'
URL_BASE = 'https://example.com/'

parser = robotparser.RobotFileParser()
parser.set_url(urljoin(URL_BASE, 'robots.txt'))
parser.read()  # ดึงและ parse

Methods หลัก

Methodคำอธิบาย
set_url(url)ตั้งค่า URL ของ robots.txt
read()ดึงและ parse robots.txt
parse(lines)parse จาก list ของ strings
can_fetch(useragent, url)True ถ้า useragent เข้าถึง url ได้
mtime()เวลาที่ fetch robots.txt ล่าสุด
modified()ตั้งค่าเวลา fetch ล่าสุด
crawl_delay(useragent)ค่า Crawl-delay (seconds)
request_rate(useragent)RequestRate(requests, seconds) tuple

ตัวอย่างการใช้งาน

from urllib import robotparser
from urllib.parse import urljoin

parser = robotparser.RobotFileParser()
parser.set_url('https://example.com/robots.txt')
parser.read()

# ตรวจสอบสิทธิ์
print(parser.can_fetch('MyBot', 'https://example.com/page.html'))   # True/False
print(parser.can_fetch('MyBot', 'https://example.com/admin/'))      # False
print(parser.can_fetch('*', 'https://example.com/downloads/file'))  # False

# Crawl delay
delay = parser.crawl_delay('MyBot')
if delay:
    print(f"Wait {delay} seconds between requests")

# Request rate
rate = parser.request_rate('MyBot')
if rate:
    print(f"{rate.requests} requests per {rate.seconds} seconds")

Best Practices สำหรับ Crawler

  1. อ่าน robots.txt ก่อน crawl ทุกครั้ง
  2. เคารพ Disallow และ Crawl-delay
  3. Cache robots.txt (เช่น 1 ชั่วโมง) ไม่ต้อง fetch ทุก request
  4. ใช้ User-Agent ที่ระบุตัวตนชัดเจน
  5. Handle errors (404, timeout) อย่างเหมาะสม
def can_crawl(url, user_agent='MyBot'):
    parser = robotparser.RobotFileParser()
    parser.set_url(urljoin(url, '/robots.txt'))
    try:
        parser.read()
        return parser.can_fetch(user_agent, url)
    except Exception:
        return True  # ถ้าอ่านไม่ได้ อนุญาต (conservative)