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 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602
|
from DrissionPage import ChromiumPage, ChromiumOptions from DrissionPage.common import By import time import re from bs4 import BeautifulSoup import os import requests import json import base64
do1 = ChromiumOptions().set_paths(local_port=9111, user_data_path=r'C:/Users/A/AppData/Local/Google/Chrome/User Data') tab = ChromiumPage(addr_or_opts=do1)
def download_images(top_limit_message_divs, download_folder, max_retries=6): if not os.path.exists(download_folder): os.makedirs(download_folder)
total_blob_images = 0
for div in top_limit_message_divs: img_tags = div.find_all('img')
for img in img_tags: img_url = img.get('src') if img_url and img_url.startswith('./'): img['src'] = 'https://web.telegram.org/a/' + img_url.lstrip('./')
filtered_img_tags = [ img for img in img_tags if not (img.find_previous_sibling('video') or img.find_next_sibling('video')) and not img.get('src', '').startswith('./') ]
blob_img_count = sum(1 for img in filtered_img_tags if img.get('src') and img.get('src').startswith('blob:')) total_blob_images += blob_img_count print(f"Found {blob_img_count} blob images in current div after filtering.")
for i, img in enumerate(filtered_img_tags): img_url = img.get('src') if img_url and img_url.startswith('blob:') and 'full-media' in img.get('class', []): message_div_id = div['id'] imgxpath = (By.XPATH, f'(//div[@id="{message_div_id}"]//img[contains(@class, "full-media") and starts-with(@src, "blob:")])') img_element = tab.ele(imgxpath) imgMorethan1xpath = (By.XPATH, f'(//div[@id="{message_div_id}"]//img[contains(@class, "full-media") and starts-with(@src, "blob:")])[2]') img_element2 = tab.ele(imgMorethan1xpath)
if img_element2: print(f"Preparing to download multi imgs") file_name = img_url.split('/')[-1] + '.jpg' img_path = os.path.join(download_folder, file_name) for attempt in range(max_retries): result = tab.run_js(f""" return fetch('{img_url}') .then(response => response.blob()) .then(blob => {{ return new Promise((resolve, reject) => {{ const reader = new FileReader(); reader.onloadend = () => resolve(reader.result.split(',')[1]); reader.onerror = reject; reader.readAsDataURL(blob); }}); }}); """)
img_data = base64.b64decode(result) with open(img_path, 'wb') as img_file: img_file.write(img_data)
time.sleep(1) if os.path.exists(img_path) and os.path.getsize(img_path) > 0: print(f"Saved image to: {img_path}") break else: print(f"Retry {attempt + 1}/{max_retries} for image {img_url} failed.") time.sleep(1) else: print(f"Failed to download image {img_url} after {max_retries} attempts.")
else: print(f"Preparing to download single img: {img_url}") img_element.scroll.to_see() time.sleep(1) tab.actions.r_click(img_element) time.sleep(1)
downloadxpath = (By.XPATH, f'//div[@id="{message_div_id}"]//div[@class="MenuItem compact" and normalize-space(.) = "Download"]') download = tab.ele(downloadxpath)
tab.set.download_path(download_folder) tab.set.download_file_name(img_url.split('/')[-1].strip()) download.click() time.sleep(1)
print(f"Total blob images found: {total_blob_images}")
def mute_autoplay_videos(message_divs): for div in message_divs: video_tags = div.find_all('video') for video in video_tags: if 'autoplay' in video.attrs: video['muted'] = '' print(f"Updated video tag: {video}")
def rename_file_extensions(directory): for filename in os.listdir(directory): base, ext = os.path.splitext(filename)
if ext == '.MP4': old_file = os.path.join(directory, filename) new_file = os.path.join(directory, base + '.mp4')
count = 1 while os.path.exists(new_file): new_file = os.path.join(directory, f"{base}_{count}.mp4") count += 1
os.rename(old_file, new_file) print(f"Renamed {filename} to {new_file}")
def is_non_chinese_and_non_link(text): return ( text and not re.search(r'[\u4e00-\u9fff]', text) and 'http' not in text and 'www' not in text and not re.search(r'^[a-zA-Z]{1,30}$', text) and not re.search(r'^@[a-zA-Z]{1,30}$', text) )
def translate_text(text): translate_tab = tab.get_tab(url='volcengine.com')
languageEn = (By.XPATH, "//div[@class='reverse']/following-sibling::div[@class='sc-ipEyDJ dqurTv']/div[@class='lang' and text()='英语']") if translate_tab.ele(languageEn): print("由于不明原因改成翻译为英文") translate_tab.ele(languageEn).click() time.sleep(2) language2 = (By.XPATH, "//div[@class='lang-search-recently']/div[@data-lang='zh']") language_option = translate_tab.ele(language2) language_option.click() print("强制改为翻译成中文")
result1 = (By.XPATH, "//div[@class='slate-editor' and @contenteditable='false']") translated_text = translate_tab.ele(result1) input1 = (By.XPATH, '//div[@role="textbox" and @aria-multiline="true" and contains(@class, "slate-editor")]') input_box = translate_tab.ele(input1) input_box.clear() input_box.input(text)
time.sleep(5) return translated_text.text
def process_webpage(url_base, message_limit): output_file_path = r'D:\hexoblog\source\telegram\telegram_translated_messages.html'
with open(output_file_path, 'w', encoding='utf-8') as file: file.write("""<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Telegram Styled Message</title> <link rel="stylesheet" href="telegram2.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css"> </head>
<script type="text/javascript"> document.addEventListener("DOMContentLoaded", function() { const lazyElements = document.querySelectorAll('.lazy');
const observer = new IntersectionObserver((entries, observer) => { entries.forEach(entry => { if (entry.isIntersecting) { const el = entry.target; const src = el.getAttribute('data-src'); if (src) { if (el.tagName === 'IMG' || el.tagName === 'VIDEO') { el.src = src; el.removeAttribute('data-src'); // 移除 data-src } observer.unobserve(el); // 停止观察已加载元素 } } }); }, { rootMargin: "0px 0px 200px 0px" }); // 提前 200px 加载
lazyElements.forEach(el => observer.observe(el)); });
</script> <body> """)
for chat_id in chat_ids: url = url_base + chat_id tab.get(url) time.sleep(3) menu1 = (By.XPATH, f'//a[@href="#-{chat_id}"]') menu_list = tab.ele(menu1) time.sleep(1) menu_list.click()
button1 = (By.XPATH, '//div[@class="Y2NKrpKj u62x81QI"]/button') buttondown = tab.ele(button1) buttondown.click() time.sleep(3) container1 = (By.XPATH, '//div[@class="messages-container"]') messages_container = tab.ele(container1) time.sleep(2)
soup = BeautifulSoup(messages_container.html, 'html.parser')
for meta_span in soup.find_all('span', class_='MessageMeta'): meta_span.decompose() for message_title in soup.find_all('span', class_='message-title-name'): message_title.decompose() for video_duration in soup.find_all('div', class_='message-media-duration'): video_duration.decompose() for button_react in soup.find_all('button', class_='message-reaction'): button_react.decompose() for reply in soup.find_all('div', class_='CommentButton'): reply.decompose() for reply2 in soup.find_all('div', class_='recent-repliers'): reply2.decompose()
message_divs = soup.find_all('div', class_='message-list-item', id=lambda x: x and x.startswith('message-'))
message_divs_sorted = sorted( message_divs, key=lambda div: int(div['id'].split('-')[1]), reverse=True )
top_limit_message_divs = message_divs_sorted[:message_limit]
for message_div in top_limit_message_divs: element = tab.ele(f'@id={message_div['id']}') element.scroll.to_see() time.sleep(1)
buttondown.click() time.sleep(3) container1 = (By.XPATH, '//div[@class="messages-container"]') messages_container = tab.ele(container1) time.sleep(2)
soup = BeautifulSoup(messages_container.html, 'html.parser')
for meta_span in soup.find_all('span', class_='MessageMeta'): meta_span.decompose() for message_title in soup.find_all('span', class_='message-title-name'): message_title.decompose() for video_duration in soup.find_all('div', class_='message-media-duration'): video_duration.decompose() for button_react in soup.find_all('button', class_='message-reaction'): button_react.decompose() for reply in soup.find_all('div', class_='CommentButton'): reply.decompose() for reply2 in soup.find_all('div', class_='recent-repliers'): reply2.decompose()
message_divs = soup.find_all('div', class_='message-list-item', id=lambda x: x and x.startswith('message-'))
message_divs_sorted = sorted( message_divs, key=lambda div: int(div['id'].split('-')[1]), reverse=True )
top_limit_message_divs = message_divs_sorted[:message_limit]
total_videos = 0 total_imgs = 0
for message_div in top_limit_message_divs:
print("处理text-content") text_content_divs = message_div.find_all('div', class_='text-content') print(f"当前的message_div的id为{message_div['id']}")
for div in text_content_divs: text_content_list = [] for text_content in div.find_all(text=True): stripped_text = text_content.strip() if is_non_chinese_and_non_link(stripped_text): text_content_list.append(stripped_text)
combined_text = '\n'.join(text_content_list) if combined_text: translated_text = translate_text(combined_text)
safe_translated_text = json.dumps(f'<p style="color: purple;">{translated_text}</p>')
target_div = tab.ele((By.XPATH, f"//div[contains(@class, 'text-content') and contains(., '{text_content_list[0]}')][not(@data-translated)]"))
if target_div: target_div.run_js("this.setAttribute('data-translated', 'true');") target_div.run_js(f""" function insertAfter(newElement, targetElement) {{ var parentElement = targetElement.parentNode; if (parentElement.lastChild === targetElement) {{ parentElement.appendChild(newElement); }} else {{ parentElement.insertBefore(newElement, targetElement.nextSibling); }} }} var transDiv = document.createElement('div'); transDiv.className = 'translated_text'; transDiv.innerHTML = {safe_translated_text}; insertAfter(transDiv, this); """) else: print("未能找到任何元素 for text-content")
print("处理WebPage-text") webpage_text_divs = message_div.find_all('div', class_='WebPage-text') print(f"当前的message_div的id为{message_div['id']}")
for div in webpage_text_divs: text_content_list = [] for text_content in div.find_all(text=True): stripped_text = text_content.strip() if is_non_chinese_and_non_link(stripped_text): text_content_list.append(stripped_text)
combined_text = '\n'.join(text_content_list) if combined_text: translated_text = translate_text(combined_text)
safe_translated_text = json.dumps(f'<p style="color: purple;">{translated_text}</p>')
if len(text_content_list) > 1: target_div = tab.ele((By.XPATH, f"//div[contains(@class, 'WebPage-text') and contains(., '{text_content_list[1]}')][not(@data-translated)]")) else: target_div = tab.ele((By.XPATH, f"//div[contains(@class, 'WebPage-text') and contains(., '{text_content_list[0]}')][not(@data-translated)]"))
if target_div: target_div.run_js("this.setAttribute('data-translated', 'true');") target_div.run_js(f""" function insertAfter(newElement, targetElement) {{ var parentElement = targetElement.parentNode; if (parentElement.lastChild === targetElement) {{ parentElement.appendChild(newElement); }} else {{ parentElement.insertBefore(newElement, targetElement.nextSibling); }} }} var transDiv = document.createElement('div'); transDiv.className = 'translated_text'; transDiv.innerHTML = {safe_translated_text}; insertAfter(transDiv, this); """) else: print("未能找到任何元素 for WebPage-text")
for message_div in top_limit_message_divs: element = tab.ele(f'@id={message_div['id']}') element.scroll.to_see() time.sleep(1)
soup = BeautifulSoup(messages_container.html, 'html.parser')
for meta_span in soup.find_all('span', class_='MessageMeta'): meta_span.decompose() for message_title in soup.find_all('span', class_='message-title-name'): message_title.decompose() for video_duration in soup.find_all('div', class_='message-media-duration'): video_duration.decompose() for button_react in soup.find_all('button', class_='message-reaction'): button_react.decompose() for reply in soup.find_all('div', class_='CommentButton'): reply.decompose() for reply2 in soup.find_all('div', class_='recent-repliers'): reply2.decompose()
message_divs = soup.find_all('div', class_='message-list-item', id=lambda x: x and x.startswith('message-'))
message_divs_sorted = sorted( message_divs, key=lambda div: int(div['id'].split('-')[1]), reverse=True )
top_limit_message_divs = message_divs_sorted[:message_limit] download_folder = r'D:\hexoblog\source\telegram' download_images(top_limit_message_divs, download_folder)
for div in top_limit_message_divs: img_tags = div.find_all('img')
for img in img_tags: img_url = img.get('src') if img_url and img_url.startswith('blob:'): new_img_url = img_url.split('/')[-1] + ".jpg" img['data-src'] = new_img_url del img['src'] if 'full-media' in img['class']: if 'lazy' not in img['class']: img['class'].append('lazy')
if img_url and img_url.startswith('./'): img_url = 'https://web.telegram.org/a/' + img_url.lstrip('./') img['src'] = img_url
max_retries = 25 for message_div in top_limit_message_divs: video_tags = message_div.find_all('video') print("Video tags found:", video_tags)
video_count = sum(1 for video in video_tags if video.get('src')) total_videos += video_count print(f"Found {video_count} videos in current div.")
if video_count > 0: for video in video_tags: video_src = video.get('src') if video_src and video_src.startswith('./progressive/document'): file_name = video_src.replace('./progressive/document', '').strip() print(f"Preparing to download video with filename: {file_name}")
message_div_id = message_div['id'] videoxpath = (By.XPATH, f'//div[@id="{message_div_id}"]//video') video_element = tab.ele(videoxpath)
tab.actions.r_click(video_element) time.sleep(1)
downloadxpath = (By.XPATH, f'//div[@id="{message_div_id}"]//div[@class="MenuItem compact" and normalize-space(.) = "Download"]') download = tab.ele(downloadxpath)
retries = 0 while retries < max_retries: try: tab.set.download_path(r'D:\hexoblog\source\telegram') tab.set.download_file_name(file_name) time.sleep(1) download.click() video_src = file_name + ".mp4" video['data-src'] = video_src del video['src'] video['class'] = 'full-media lazy' print(f"Downloaded {file_name} successfully.") break except Exception as e: retries += 1 print(f"错误: {e}. 重试 ({retries}/{max_retries})...") time.sleep(3) else: print(f"Failed to download {file_name} after {max_retries} attempts.") time.sleep(15)
mute_autoplay_videos(top_limit_message_divs)
directory_path = "D:/hexoblog/source/telegram"
for filename in os.listdir(directory_path): if filename.startswith("video"): new_filename = filename[len("video"):] old_file = os.path.join(directory_path, filename) new_file = os.path.join(directory_path, new_filename)
count = 1 while os.path.exists(new_file): new_file = os.path.join(directory_path, f"{new_filename}_{count}") count += 1
os.rename(old_file, new_file) print(f"Renamed {filename} to {new_file}")
rename_file_extensions(directory_path)
for filename in os.listdir(directory_path): if filename.endswith('_1.mp4') or filename.endswith('_1.MOV'): new_filename = filename.replace('_1', '', 1) old_file = os.path.join(directory_path, filename) new_file = os.path.join(directory_path, new_filename) count = 1 while os.path.exists(new_file): name, ext = os.path.splitext(new_filename) new_file = os.path.join(directory_path, f"{name}_new{count}{ext}") count += 1
os.rename(old_file, new_file) print(f"Renamed {filename} to {new_file}") else: print(f"Skipping {filename}, does not match pattern.")
translated_text_divs = ''.join(str(div) for div in top_limit_message_divs)
for div in translated_text_divs: with open(output_file_path, 'a', encoding='utf-8') as file: file.write(str(div)) with open(output_file_path, 'a', encoding='utf-8') as file: file.write("\n</body>\n</html>")
print(f"Translated messages saved to {output_file_path}")
chat_ids = ['1001036240821', '1001374600389', '1001576917998', '1001375124677', '1001001746107', '1001394050290'] url_base = 'https://web.telegram.org/a/#-' message_limit = 25
process_webpage(url_base, message_limit)
|
评论