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
| import os import re import xbot import requests import pymysql from bs4 import BeautifulSoup from xbot import print, sleep,web from .import package from .package import variables as glv from urllib.parse import urljoin from datetime import datetime
DB_CONFIG = { 'host': '192.168.200.129', 'user': 'root', 'password': 'root123456', 'database': 'test', 'charset': 'utf8mb4' }
def save_to_mysql(title, dept, post_date, zihao, level, timeliness, content, attachment_count, attachment_path, link):
try: connection = pymysql.connect(**DB_CONFIG) try: post_date = datetime.strptime(post_date, '%Y-%m-%d').date() except: post_date = None
title = title[:255] if len(title) > 255 else title with connection.cursor() as cursor: check_sql = """ SELECT 1 FROM hwz_yaozhi WHERE link = %s """ cursor.execute(check_sql,link) exists = cursor.fetchone() if exists: sql = """ UPDATE hwz_yaozhi SET title = %s, dept = %s, post_date = %s, zihao = %s, level = %s, timeliness = %s, content = %s, attachment_count = %s, attachment_path = %s, update_time = CURRENT_TIMESTAMP WHERE link = %s """ cursor.execute(sql, (title, dept, post_date, zihao, level, timeliness, content, attachment_count, attachment_path, link)) print(f"更新数据库记录: {title} - {link}") else: sql = """ INSERT INTO hwz_yaozhi ( title, dept, post_date, zihao, level, timeliness, content, attachment_count, attachment_path, link ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s) """ cursor.execute(sql, (title, dept, post_date, zihao, level, timeliness, content, attachment_count, attachment_path, link)) print(f"新增数据库记录: {title} - {link}") connection.commit() except pymysql.Error as e: print(f"数据库操作失败: {str(e)}") if connection: connection.rollback() finally: if connection: connection.close()
def download_attachments(web_object, title, base_url):
safe_title = "".join([c for c in title if c.isalpha() or c.isdigit() or c in (' ', '-', '_')]).rstrip() safe_title = safe_title[:100] if len(safe_title) > 100 else safe_title safe_title = safe_title.strip().strip('.') base_dir = r"D:\WorkSpace\RPA_project\attachments\yaozhi" save_dir = os.path.join(base_dir, safe_title) os.makedirs(save_dir, exist_ok=True) attachment_links = web_object.find_all_by_xpath("//a[contains(@href, '.pdf') or contains(@href, '.doc') or contains(@href, '.xls') or contains(@href, '.zip') or contains(@href, '.rar')]") downloaded_files = [] for link_element in attachment_links: file_url = link_element.get_attribute("href") file_name = link_element.get_text().strip() if not file_url.startswith("http"): file_url = urljoin(base_url, file_url) if not file_name or file_name == "": file_name = os.path.basename(file_url) else: ext = os.path.splitext(file_url)[1] if not file_name.endswith(ext): file_name += ext file_path = os.path.join(save_dir, file_name) if os.path.exists(file_path): print(f"附件已存在,跳过下载: {file_name}") continue try: print(f"正在下载附件: {file_name}") response = requests.get(file_url, stream=True, timeout=30) response.raise_for_status() with open(file_path, "wb") as f: for chunk in response.iter_content(chunk_size=8192): if chunk: f.write(chunk) downloaded_files.append(file_name) print(f"附件下载完成: {file_name}") except Exception as e: print(f"下载附件失败: {file_name}, 错误: {str(e)}") total_files = len(os.listdir(save_dir)) if os.path.exists(save_dir) else 0 return downloaded_files, total_files, save_dir
def get_page(title, link, dept, post_date): print(f"正在获取:{title},{link}") base_url = "/".join(link.split("/")[:3]) + "/"
MAX_RETRIES = 3 for attempt in range(MAX_RETRIES + 1): try: web_object = web.create(link, 'edge', load_timeout=30) break except Exception as e: if attempt < MAX_RETRIES: print(f"页面加载失败,第 {attempt+1} 次重试: {str(e)}") sleep(2) else: print(f"页面加载超时,已尝试 {MAX_RETRIES+1} 次: {str(e)}") web_object = None break
zihao = "" level = "" timeliness = "" content = ""
try: info_items = web_object.find_all_by_xpath('//div[@class="manual"]/div[contains(@class, "content")]') for item in info_items: try: span = item.find_by_xpath('./span') if span: span_text = span.get_text().strip() if span_text.startswith("【"): item_text = item.get_text().strip() value = item_text.replace(span_text, "", 1).strip() if "发文字号" in span_text: zihao = value elif "效力级别" in span_text: level = value elif "时效" in span_text.replace(" ", ""): timeliness = value except: continue except Exception as e: print(f"提取信息项时出错: {e}")
try: content_div = web_object.find_by_xpath('//div[@class="text"]') if content_div: content = content_div.get_text().strip() except: try: content_div = web_object.find_by_xpath('//div[@class="new_detail_content"]') if content_div: content = content_div.get_text().strip() except: try: content_div = web_object.find_by_xpath('//div[contains(@class, "content")]//div[@class="text"]') if content_div: content = content_div.get_text().strip() except: try: content_div = web_object.find_by_xpath('//div[contains(@class, "content")]//div[@class="new_detail_content"]') if content_div: content = content_div.get_text().strip() except: try: manual_div = web_object.find_by_xpath('//div[@class="manual"]') if manual_div: content = manual_div.get_text().strip() except Exception as e: print(f"提取内容时出错: {e}") content = "无法提取内容"
print(f"发文字号: {zihao}") print(f"效力级别: {level}") print(f"时效性: {timeliness}") print(f"文章内容: {content}") downloaded_files, attachment_count, attachment_path = download_attachments(web_object, title, base_url) print(f"已创建文件路径:{attachment_path}") if downloaded_files: print(f"成功下载 {len(downloaded_files)} 个附件,当前共有 {attachment_count} 个附件") else: print(f"没有新附件需要下载,当前共有 {attachment_count} 个附件")
save_to_mysql(title, dept, post_date, zihao, level, timeliness, content, attachment_count, attachment_path, link)
web_object.close()
def get_list(): base_url = 'https://db.yaozh.com/policies' max_page = 3 for page in range(1, max_page + 1): url = f"{base_url}?p={page}.html" print(f"开始爬取第 {page}/{max_page} 页") web_object = web.create(url, 'edge', load_timeout=30) elements = web_object.find_all_by_xpath("/html/body/div[7]/div[6]/div/div[2]/table/tbody/tr") for element in elements: title = element.child_at(0).get_text().strip() link = "https://db.yaozh.com" + element.find_by_xpath("./th/a").get_attribute("href") dept = element.child_at(1).get_text().strip() post_date = element.child_at(2).get_text().strip() get_page(title, link, dept, post_date) web_object.close() sleep(2)
def main(args): get_list()
|