main.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. import os
  2. import time
  3. import random
  4. import httpx
  5. from bs4 import BeautifulSoup
  6. comico_urls = [
  7. '[PIXIV] LotteryFate (18900473)(AI)',
  8. ]
  9. # 是否使用代理
  10. use_proxy = 1
  11. def save_img(client, folder_path, img_links):
  12. for index, img_url in enumerate(img_links, start=1):
  13. try:
  14. # 生成文件名,例如 0001.png, 0002.png
  15. file_name = f"{str(index).zfill(4)}.png"
  16. file_path = os.path.join(folder_path, file_name)
  17. # 检查文件是否已经存在
  18. if os.path.exists(file_path):
  19. print(f"文件已存在,跳过下载: {file_path}")
  20. continue
  21. # 发送请求获取图片内容
  22. response = client.get(img_url)
  23. if response.status_code != 200:
  24. raise Exception(
  25. f"无法下载图片 {img_url},状态码: {response.status_code}")
  26. # 保存图片到本地
  27. with open(file_path, 'wb') as file:
  28. file.write(response.content)
  29. print(f"图片已保存: {file_path}")
  30. except Exception as e:
  31. raise Exception(f"下载图片 {img_url} 时出错: {e}")
  32. # random_sleep = random.uniform(2, 3)
  33. # print(f"随机休眠 {random_sleep} 秒")
  34. # time.sleep(random_sleep)
  35. def get_imgs(client, folder_path, chapter_data):
  36. img_links = []
  37. for chapter_name, url in chapter_data.items():
  38. try:
  39. # 发送请求获取页面内容
  40. response = client.get(url)
  41. if response.status_code != 200:
  42. raise Exception(f"无法访问 {url},状态码: {response.status_code}")
  43. # 解析 HTML
  44. soup = BeautifulSoup(response.text, 'html.parser')
  45. # 获取图片的上一层元素
  46. parent_element = soup.select_one(
  47. 'body > div.container > div.row.col-lg-12.col-md-12.col-xs-12')
  48. if not parent_element:
  49. raise Exception(f"{chapter_name} 未找到图片容器")
  50. # 获取所有图片元素
  51. img_elements = parent_element.select('img')
  52. total_images = len(img_elements)
  53. print(f'{chapter_name} 共 {total_images} 张图片')
  54. # 输出图片的 URL
  55. for img in img_elements:
  56. img_url = img.get('src')
  57. if img_url:
  58. img_links.append(img_url)
  59. except Exception as e:
  60. print(f"获取图片时出错: {e}")
  61. raise # 抛出异常,触发重试逻辑
  62. return img_links
  63. def save_urls(folder_path, img_links):
  64. # 定义保存文件路径
  65. save_path = os.path.join(folder_path, 'img_links.txt')
  66. # 将图片链接写入文件
  67. with open(save_path, 'w', encoding='utf-8') as file:
  68. for link in img_links:
  69. file.write(link + '\n')
  70. print(f"图片链接已保存到: {save_path}")
  71. def new_folder(page_title):
  72. # 获取当前脚本所在的目录
  73. script_dir = os.path.dirname(os.path.abspath(__file__))
  74. download_dir = os.path.join(script_dir, 'downloads')
  75. if not os.path.exists(script_dir):
  76. os.makedirs(script_dir)
  77. if page_title:
  78. # 拼接目标文件夹路径
  79. folder_path = os.path.join(download_dir, page_title)
  80. # 检查文件夹是否存在,如果不存在则创建
  81. if not os.path.exists(folder_path):
  82. os.makedirs(folder_path)
  83. return folder_path
  84. def get_chapter_data(client, target_url):
  85. result = {}
  86. page_title = ''
  87. try:
  88. response = client.get(target_url)
  89. if response.status_code != 200:
  90. raise Exception(f"无法访问 {target_url},状态码: {response.status_code}")
  91. soup = BeautifulSoup(response.text, 'html.parser')
  92. # 获取指定选择器下的所有元素
  93. elements = soup.select(
  94. 'body > div.container > div:nth-child(3) > div:nth-child(2) a')
  95. # 提取每个元素的 URL 和文本
  96. for element in elements:
  97. url = element.get('href')
  98. text = element.get_text()
  99. result[text] = base_url + url
  100. except Exception as e:
  101. print(f"获取章节数据时出错: {e}")
  102. raise # 抛出异常,触发重试逻辑
  103. return result
  104. def main():
  105. proxy_url = 'http://127.0.0.1:7890'
  106. base_url = 'https://jcomic.net'
  107. herf_url = '/eps/'
  108. # 自定义请求头
  109. custom_headers = {
  110. "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
  111. "accept-language": "zh-CN,zh;q=0.9",
  112. "cache-control": "max-age=0",
  113. "cookie": "_gid=GA1.2.724162267.1736817775; _ga_QL6YSDRWEV=GS1.1.1736837388.3.0.1736837388.0.0.0; _ga=GA1.2.1324234734.1736817774; _gat=1",
  114. "priority": "u=0, i",
  115. "sec-ch-ua": '"Google Chrome";v="131", "Chromium";v="131", "Not_A Brand";v="24"',
  116. "sec-ch-ua-mobile": "?0",
  117. "sec-ch-ua-platform": '"macOS"',
  118. "sec-fetch-dest": "document",
  119. "sec-fetch-mode": "navigate",
  120. "sec-fetch-site": "same-origin",
  121. "sec-fetch-user": "?1",
  122. "upgrade-insecure-requests": "1",
  123. "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
  124. }
  125. for comico_url in comico_urls:
  126. target_url = base_url + herf_url + comico_url
  127. print(target_url)
  128. # 最大重试次数
  129. max_retries = 999
  130. retry_count = 0
  131. while retry_count < max_retries:
  132. try:
  133. # 创建 httpx.Client 实例,并设置自定义请求头
  134. with httpx.Client(proxies=proxy_url if use_proxy else None, headers=custom_headers) as client:
  135. # 1, 获取页面章节数据
  136. chapter_data = get_chapter_data(client, target_url)
  137. print(chapter_data)
  138. # 2, 在当前文件夹下创建一个文件夹,用来保存图片, 文件名称是 title
  139. folder_path = new_folder(comico_url)
  140. # 3, 遍历章节数据,获取img的链接
  141. img_links = get_imgs(client, folder_path, chapter_data)
  142. print(img_links)
  143. # 4, 保存url到新建的文件夹中
  144. save_urls(folder_path, img_links)
  145. # 5,遍历 img_links ,将图片保存到 folder_path中, 保存的文件名类似 0001.png
  146. save_img(client, folder_path, img_links)
  147. # 如果成功执行完成,跳出循环
  148. print('done!')
  149. break
  150. except Exception as e:
  151. retry_count += 1
  152. print(f"发生错误: {e},正在进行第 {retry_count} 次重试...")
  153. if retry_count >= max_retries:
  154. print("已达到最大重试次数,程序终止。")
  155. break
  156. # 固定延迟 10 分钟(600 秒)
  157. delay = 30
  158. print(f"等待 {delay} 秒后重试...")
  159. time.sleep(delay)
  160. if __name__ == '__main__':
  161. main()