1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
| import requests from bs4 import BeautifulSoup import os import time from urllib.parse import urljoin import hashlib import json from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException, NoSuchElementException import re import urllib.parse
class PillowfortScraper: def __init__(self): self.session = requests.Session() self.base_url = 'https://www.pillowfort.social' self.download_history_file = 'download_history.json' self.download_history = self.load_download_history(self.download_history_file) options = webdriver.ChromeOptions() options.add_argument('--headless') self.driver = webdriver.Chrome(options=options) self.default_tag = 'bakertoons' def __del__(self): """Cleanup when the scraper is destroyed""" if hasattr(self, 'driver'): self.driver.quit()
def load_download_history(self, history_file): """Load download history from JSON file""" try: with open(history_file, 'r') as f: return json.load(f) except FileNotFoundError: return {'urls': {}, 'downloaded': {}} def save_download_history(self, history_file, history): """Save download history to JSON file""" with open(history_file, 'w') as f: json.dump(history, f) def get_url_hash(self, url): """Generate a hash for the URL""" return hashlib.md5(url.encode()).hexdigest()
def login(self, email, password): """Login to Pillowfort account""" login_url = urljoin(self.base_url, '/login') print("Attempting to log in...") try: response = self.session.get(login_url) soup = BeautifulSoup(response.text, 'html.parser') auth_token = soup.find('input', {'name': 'authenticity_token'})['value'] login_data = { 'user[email]': email, 'user[password]': password, 'authenticity_token': auth_token } response = self.session.post(login_url, data=login_data) if response.ok: print("Successfully logged in!") return True else: print(f"Login failed. Status code: {response.status_code}") return False except Exception as e: print(f"Login error: {str(e)}") return False
def get_original_image_url(self, url): """Convert thumbnail URL to original size URL""" return url.replace('thumbnail_', 'original_')
def scroll_to_bottom(self): """Scroll to bottom of page to trigger lazy loading""" self.driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") time.sleep(2)
def has_next_page(self): """Check if there are more posts to load""" try: next_button = self.driver.find_elements(By.XPATH, '//*[@id="userBlogPosts"]/div/dir-pagination-controls/ul/li[last()]/a') if next_button and 'disabled' not in next_button[0].find_element(By.XPATH, '..').get_attribute('class'): return True return False except NoSuchElementException: return False
def get_user_posts(self, username, tag=None): try: tag = tag or self.default_tag encoded_tag = urllib.parse.quote(tag) url = f"{self.base_url}/{username}/tagged/{encoded_tag}" print(f"\nStarting scrape from: {url}") self.driver.get(url) post_data = [] page = 1 total_images = 0 while True: print(f"\nScraping page {page}...") try: print("Waiting for posts to load...") WebDriverWait(self.driver, 10).until( EC.presence_of_element_located((By.CLASS_NAME, "post")) ) except TimeoutException: print("Timeout waiting for posts to load") break
time.sleep(2)
soup = BeautifulSoup(self.driver.page_source, 'html.parser') posts = soup.find_all("div", class_="post") print(f"Found {len(posts)} posts on page {page}") page_images = 0 for post_idx, post in enumerate(posts, 1): content = post.find("div", class_="post-content") if not content: continue images = [] for img in content.find_all("img"): src = img.get("src") if src and not src.endswith(".svg"): original_src = src.replace("_small", "") filename = self.get_image_filename(original_src) images.append({ 'url': original_src, 'filename': filename }) page_images += 1 if images: post_data.append({ "images": images }) total_images += page_images print(f"Found {page_images} images on page {page}") print(f"Total images found so far: {total_images}") print("\nLooking for next page...") if not self.click_next_page(): print("No more pages available") break page += 1 print("Waiting for next page to load...") time.sleep(2) print(f"\nScraping complete!") print(f"Total pages scraped: {page}") print(f"Total posts with images: {len(post_data)}") print(f"Total images found: {total_images}") return post_data
except Exception as e: print(f"\nError during scraping: {str(e)}") return []
def download_images(self, username, save_dir, tag=None): """Download images with original filenames and handle history""" try: tag = tag or self.default_tag save_dir = os.path.join(save_dir, username, tag) history_file = os.path.join(save_dir, 'download_history.json') if not os.path.exists(save_dir): os.makedirs(save_dir) print(f"\nCreated directory: {save_dir}") history = self.load_download_history(history_file) print("\nStarting scraping process...") print("Press Ctrl+C to exit gracefully") posts = [] page = 1 found_existing = False while True: print(f"\nScraping page {page}...") current_posts = self.get_user_posts(username, tag) for post in current_posts: new_images = [] for image in post['images']: url = image['url'] url_hash = self.get_url_hash(url) if url_hash in history['urls'] and history['downloaded'].get(url_hash, False): found_existing = True continue new_images.append(image) history['urls'][url_hash] = { 'url': url, 'filename': image['filename'], 'timestamp': time.time() } if new_images: posts.append({'images': new_images}) if found_existing and not any(post['images'] for post in posts): print("Reached previously downloaded content, stopping...") break if not self.click_next_page(): print("No more pages available") break page += 1 if not posts: print("No new images to download") return total_images = sum(len(post['images']) for post in posts) print(f"\nStarting download of {total_images} new images...") print(f"Files will be saved to: {save_dir}") downloaded = 0 failed = 0 for post_idx, post in enumerate(posts, 1): for image in post['images']: try: url = image['url'] url_hash = self.get_url_hash(url) filename = image['filename'] save_path = os.path.join(save_dir, filename) if os.path.exists(save_path) and history['downloaded'].get(url_hash, False): print(f"Skipping already downloaded: {filename}") continue print(f"Downloading: {filename}") response = requests.get(url, timeout=10) if response.status_code == 200: with open(save_path, 'wb') as f: f.write(response.content) downloaded += 1 history['downloaded'][url_hash] = True print(f"✓ Success ({downloaded}/{total_images})") else: failed += 1 history['downloaded'][url_hash] = False print(f"✗ Skipped: HTTP {response.status_code}") continue except requests.Timeout: failed += 1 history['downloaded'][url_hash] = False print(f"✗ Skipped: Download timeout") continue except Exception as e: failed += 1 history['downloaded'][url_hash] = False print(f"✗ Skipped: {str(e)}") continue if downloaded % 5 == 0: self.save_download_history(history_file, history) print(f"\nProgress: {downloaded}/{total_images} downloaded, {failed} skipped") self.save_download_history(history_file, history) print(f"\nDownload complete!") print(f"Successfully downloaded: {downloaded} new images") print(f"Skipped downloads: {failed} images") print(f"Files saved in: {save_dir}")
except KeyboardInterrupt: print("\n\nGracefully exiting...") print("Saving download history...") self.save_download_history(history_file, history) print(f"Progress saved: {downloaded}/{total_images} downloaded") print("You can resume the download later") return
def get_image_filename(self, url): """Extract original filename from URL""" path = urllib.parse.urlparse(url).path base_name = os.path.basename(path) base_name = base_name.replace('_small', '') return base_name
def click_next_page(self): """Click the next page button if available""" try: next_button = self.driver.find_element(By.XPATH, '//*[@id="userBlogPosts"]/div/dir-pagination-controls/ul/li[last()]/a') parent_li = next_button.find_element(By.XPATH, '..') if 'disabled' in parent_li.get_attribute('class'): print("Reached last page") return False self.driver.execute_script("arguments[0].scrollIntoView(true);", next_button) time.sleep(1) print("Found next page button, clicking...") try: next_button.click() except: self.driver.execute_script("arguments[0].click();", next_button) time.sleep(2) return True except NoSuchElementException: print("No next page button found") return False except Exception as e: print(f"Error clicking next page: {str(e)}") return False
def get_user_posts_with_pagination(self, username, tag=None, max_pages=None): """Get all posts from a user's blog, optionally filtered by tag, with pagination handling""" posts = [] page = 1 while True: print(f"Scraping page {page}...") current_posts = self.get_user_posts(username, tag) if not current_posts: print("No more posts to load") break posts.extend(current_posts) if not self.click_next_page(): print("No more pages to load") break page += 1 time.sleep(1) print(f"Found {len(posts)} posts with images") return posts
def download_images_with_pagination(self, save_dir, username, tag=None): """Download images with original filenames and handle pagination""" if not os.path.exists(save_dir): os.makedirs(save_dir) posts = self.get_user_posts_with_pagination(username, tag) total_images = sum(len(self.extract_images(post)) for post in posts) print(f"Starting download of {total_images} images...") downloaded = 0 for post in posts: images = self.extract_images([post]) for image in images: try: filename = self.get_image_filename(image) save_path = os.path.join(save_dir, filename) response = self.session.get(image) if response.status_code == 200: with open(save_path, 'wb') as f: f.write(response.content) downloaded += 1 print(f"Downloaded {downloaded}/{total_images}: {filename}") else: print(f"Failed to download {filename}: HTTP {response.status_code}") except Exception as e: print(f"Error downloading {filename}: {str(e)}") print(f"Download complete. Successfully downloaded {downloaded} images.")
def main(): try: scraper = PillowfortScraper() default_email = "YOUR EMAIL" default_password = "YOUR PASSWORD" default_username = "bakertoons" default_save_dir = os.getcwd() print("Press Ctrl+C at any time to exit gracefully") email = input(f"Enter your Pillowfort email [{default_email}]: ").strip() email = email if email else default_email password = input(f"Enter your Pillowfort password [{default_password}]: ").strip() password = password if password else default_password username = input(f"Enter the username to scrape [{default_username}]: ").strip() username = username if username else default_username tag = input(f"Enter tag to search for [{scraper.default_tag}]: ").strip() tag = tag if tag else scraper.default_tag save_dir = default_save_dir if not scraper.login(email, password): print("Exiting due to login failure.") return print("\nStarting download process...") scraper.download_images(username, save_dir, tag)
except KeyboardInterrupt: print("\nExiting program...") finally: if hasattr(scraper, 'driver'): scraper.driver.quit() print("Goodbye!")
if __name__ == "__main__": main()
|