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
| """ 网站数据抓取与汇总工具(含登录验证版) """ import os import re import time import requests from bs4 import BeautifulSoup import pandas as pd from typing import List, Dict, Optional from urllib.parse import urljoin from requests.adapters import HTTPAdapter from requests.exceptions import RequestException
class Config: """爬虫配置参数""" def __init__(self): self.base_url = "https://example.com" self.login_url = "https://example.com/login" self.list_url_template = "/news?page={page}" self.start_page = 1 self.end_page = 3 self.username = "your_username" self.password = "your_password" self.headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36', 'Referer': 'https://example.com/' } self.timeout = 10 self.retries = 3 self.retry_delay = 5 self.output_dir = "scraped_data" self.excel_file = "summary.xlsx" os.makedirs(self.output_dir, exist_ok=True)
class WebScraper: """网站爬取处理器""" def __init__(self, config: Config): self.config = config self.session = requests.Session() self.session.mount('https://', HTTPAdapter(max_retries=config.retries)) def login(self) -> bool: """执行登录操作""" try: login_page = self._safe_request( 'GET', self.config.login_url, allow_redirects=False ) soup = BeautifulSoup(login_page.text, 'html.parser') csrf_token = soup.find('input', {'name': 'csrf_token'})['value'] login_data = { 'username': self.config.username, 'password': self.config.password, 'csrf_token': csrf_token } response = self._safe_request( 'POST', self.config.login_url, data=login_data, allow_redirects=False ) if response.status_code == 302 and 'sessionid' in response.cookies: print("登录成功") return True print("登录失败") return False except Exception as e: print(f"登录过程发生异常: {str(e)}") return False def fetch_pages(self) -> List[Dict]: """抓取所有页面数据""" all_data = [] for page in range(self.config.start_page, self.config.end_page + 1): print(f"正在处理第 {page} 页...") list_url = urljoin( self.config.base_url, self.config.list_url_template.format(page=page) ) try: list_response = self._safe_request('GET', list_url) article_links = self._parse_list_page(list_response.text) for i, link in enumerate(article_links, 1): article_url = urljoin(self.config.base_url, link) print(f" 正在处理文章 {i}/{len(article_links)}: {article_url}") article_data = self._fetch_article(article_url) if article_data: all_data.append(article_data) time.sleep(1) except Exception as e: print(f"第 {page} 页处理失败: {str(e)}") continue return all_data def _fetch_article(self, url: str) -> Optional[Dict]: """抓取单篇文章内容""" try: response = self._safe_request('GET', url) return self._parse_article_page(response.text, url) except Exception as e: print(f"文章抓取失败: {url} - {str(e)}") return None def _parse_list_page(self, html: str) -> List[str]: """解析列表页获取文章链接""" soup = BeautifulSoup(html, 'html.parser') links = [] for item in soup.select('.article-list .title a'): if href := item.get('href'): links.append(href) return links def _parse_article_page(self, html: str, url: str) -> Dict: """解析文章详情页""" soup = BeautifulSoup(html, 'html.parser') def safe_extract(selector: str, default: str = "") -> str: element = soup.select_one(selector) return element.text.strip() if element else default return { 'title': safe_extract('h1.article-title'), 'author': safe_extract('.author-name'), 'publish_date': safe_extract('.publish-time'), 'content': safe_extract('.article-content'), 'url': url } def _safe_request(self, method: str, url: str, **kwargs) -> requests.Response: """带异常处理和重试机制的请求方法""" for attempt in range(self.config.retries + 1): try: response = self.session.request( method=method, url=url, headers=self.config.headers, timeout=self.config.timeout, **kwargs ) response.raise_for_status() return response except RequestException as e: if attempt < self.config.retries: print(f"请求失败,第 {attempt+1} 次重试: {str(e)}") time.sleep(self.config.retry_delay) else: raise
class DataHandler: """数据处理与存储""" @staticmethod def save_text(data: Dict, output_dir: str) -> str: """保存为文本文件""" try: filename = re.sub(r'[^\w\-_\. ]', '_', data.get('title', 'untitled'))[:50] filename = f"{filename}.txt" filepath = os.path.join(output_dir, filename) with open(filepath, 'w', encoding='utf-8') as f: for key, value in data.items(): f.write(f"=== {key.upper()} ===\n{value}\n\n") return filepath except Exception as e: print(f"文件保存失败: {str(e)}") return "" @staticmethod def save_excel(data: List[Dict], filename: str) -> bool: """保存为Excel文件""" try: df = pd.DataFrame(data) df['publish_date'] = pd.to_datetime(df['publish_date'], errors='coerce') df.to_excel( filename, index=False, engine='openpyxl', encoding='utf-8' ) return True except Exception as e: print(f"Excel保存失败: {str(e)}") return False
def main(): config = Config() scraper = WebScraper(config) if not scraper.login(): print("登录失败,程序终止") return try: articles = scraper.fetch_pages() print(f"共抓取到 {len(articles)} 篇文章") except Exception as e: print(f"抓取过程发生严重错误: {str(e)}") return saved_files = [] for article in articles: if path := DataHandler.save_text(article, config.output_dir): saved_files.append(path) if DataHandler.save_excel(articles, config.excel_file): print(f"数据已汇总保存至 {config.excel_file}")
if __name__ == "__main__": main()
|