Upload .\src\data_collection\web_utils.py with huggingface_hub
Browse files
.//src//data_collection//web_utils.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shared utilities for web scraping with robots.txt compliance."""
|
| 2 |
+
|
| 3 |
+
import logging
|
| 4 |
+
import time
|
| 5 |
+
from urllib.parse import urlparse
|
| 6 |
+
from urllib.robotparser import RobotFileParser
|
| 7 |
+
|
| 8 |
+
logger = logging.getLogger(__name__)
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def check_robots_txt(url: str, user_agent: str = "BwengeAi/0.1", delay: float = 2.0) -> bool:
|
| 12 |
+
"""Check if scraping a URL is allowed by robots.txt.
|
| 13 |
+
|
| 14 |
+
Returns True if allowed, False if disallowed.
|
| 15 |
+
On error (can't reach robots.txt), returns True with a warning.
|
| 16 |
+
"""
|
| 17 |
+
try:
|
| 18 |
+
parsed = urlparse(url)
|
| 19 |
+
robots_url = f"{parsed.scheme}://{parsed.netloc}/robots.txt"
|
| 20 |
+
|
| 21 |
+
rp = RobotFileParser()
|
| 22 |
+
rp.set_url(robots_url)
|
| 23 |
+
rp.read()
|
| 24 |
+
|
| 25 |
+
if not rp.can_fetch(user_agent, url):
|
| 26 |
+
logger.warning(f"robots.txt disallows fetching: {url}")
|
| 27 |
+
return False
|
| 28 |
+
|
| 29 |
+
crawl_delay = rp.crawl_delay(user_agent)
|
| 30 |
+
if crawl_delay and crawl_delay > delay:
|
| 31 |
+
logger.info(f"robots.txt requests delay of {crawl_delay}s for {parsed.netloc}")
|
| 32 |
+
|
| 33 |
+
return True
|
| 34 |
+
|
| 35 |
+
except Exception as e:
|
| 36 |
+
logger.warning(f"Could not read robots.txt for {url}: {e}. Proceeding with caution.")
|
| 37 |
+
return True
|