You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

348 lines
13 KiB

1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
  1. # 控制流程的暂停和继续
  2. import csv
  3. import datetime
  4. import json
  5. import os
  6. import re
  7. import time
  8. import uuid
  9. import keyboard
  10. from openpyxl import Workbook, load_workbook
  11. import requests
  12. from urllib.parse import urlparse
  13. import pymysql
  14. from lxml import etree
  15. def is_valid_url(url):
  16. try:
  17. result = urlparse(url)
  18. return all([result.scheme, result.netloc])
  19. except ValueError:
  20. return False
  21. def lowercase_tags_in_xpath(xpath):
  22. return re.sub(r"([A-Z]+)(?=[\[\]//]|$)", lambda x: x.group(0).lower(), xpath)
  23. def on_press_creator(press_time, event):
  24. def on_press(key):
  25. try:
  26. if key.char == 'p':
  27. if press_time["is_pressed"] == False: # 没按下p键时,记录按下p键的时间
  28. press_time["duration"] = time.time()
  29. press_time["is_pressed"] = True
  30. else: # 按下p键时,判断按下p键的时间是否超过2.5秒
  31. duration = time.time() - press_time["duration"]
  32. if duration > 2:
  33. if event._flag == False:
  34. print("任务执行中,长按p键暂停执行。")
  35. print("Task is running, long press 'p' to pause.")
  36. # 设置Event的值为True,使得线程b可以继续执行
  37. event.set()
  38. else:
  39. # 设置Event的值为False,使得线程b暂停执行
  40. print("任务已暂停,长按p键继续执行...")
  41. print("Task paused, long press 'p' to continue...")
  42. event.clear()
  43. press_time["duration"] = time.time()
  44. press_time["is_pressed"] = False
  45. # print("按下p键时间:", press_time["duration"])
  46. except:
  47. pass
  48. return on_press
  49. def on_release_creator(event, press_time):
  50. def on_release(key):
  51. try:
  52. # duration = time.time() - press_time["duration"]
  53. # # print("松开p键时间:", time.time(), "Duration: ", duration)
  54. # if duration > 2.5 and key.char == 'p':
  55. # if event._flag == False:
  56. # print("任务执行中,按p键暂停执行。")
  57. # print("Task is running, press 'p' to pause.")
  58. # # 设置Event的值为True,使得线程b可以继续执行
  59. # event.set()
  60. # else:
  61. # # 设置Event的值为False,使得线程b暂停执行
  62. # print("任务已暂停,按p键继续执行...")
  63. # print("Task paused, press 'p' to continue...")
  64. # event.clear()
  65. # press_time["duration"] = time.time()
  66. press_time["is_pressed"] = False
  67. except:
  68. pass
  69. return on_release
  70. def check_pause(key, event):
  71. while True:
  72. if keyboard.is_pressed(key): # 按下p键,暂停程序
  73. if event._flag == False:
  74. print("任务执行中,长按p键暂停执行。")
  75. print("Task is running, long press 'p' to pause.")
  76. # 设置Event的值为True,使得线程b可以继续执行
  77. event.set()
  78. else:
  79. # 设置Event的值为False,使得线程b暂停执行
  80. print("任务已暂停,长按p键继续执行...")
  81. print("Task paused, press 'p' to continue...")
  82. event.clear()
  83. time.sleep(1) # 每秒检查一次
  84. def download_image(url, save_directory):
  85. # 定义浏览器头信息
  86. headers = {
  87. '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'
  88. }
  89. if is_valid_url(url):
  90. # 发送 GET 请求获取图片数据
  91. response = requests.get(url, headers=headers)
  92. # 检查响应状态码是否为成功状态
  93. if response.status_code == requests.codes.ok:
  94. # 提取文件名
  95. file_name = url.split('/')[-1].split("?")[0]
  96. # 生成唯一的新文件名
  97. new_file_name = file_name + '_' + \
  98. str(uuid.uuid4()) + '_' + file_name
  99. # 构建保存路径
  100. save_path = os.path.join(save_directory, new_file_name)
  101. # 保存图片到本地
  102. with open(save_path, 'wb') as file:
  103. file.write(response.content)
  104. print("图片已成功下载到:", save_path)
  105. print("The image has been successfully downloaded to:", save_path)
  106. else:
  107. print("下载图片失败,请检查此图片链接是否有效:", url)
  108. print(
  109. "Failed to download image, please check if this image link is valid:", url)
  110. else:
  111. print("下载图片失败,请检查此图片链接是否有效:", url)
  112. print("Failed to download image, please check if this image link is valid:", url)
  113. def get_output_code(output):
  114. try:
  115. if output.find("rue") != -1: # 如果返回值中包含true
  116. code = 1
  117. else:
  118. code = int(output)
  119. except:
  120. code = 0
  121. return code
  122. # 判断字段是否为空
  123. def isnull(s):
  124. return len(s) != 0
  125. def new_line(outputParameters, maxViewLength, record):
  126. line = []
  127. i = 0
  128. for value in outputParameters.values():
  129. line.append(value)
  130. if record[i]:
  131. print(value[:maxViewLength], " ", end="")
  132. i += 1
  133. print("")
  134. return line
  135. def write_to_csv(file_name, data, record):
  136. with open(file_name, 'a', encoding='utf-8-sig', newline="") as f:
  137. f_csv = csv.writer(f)
  138. for line in data:
  139. to_write = []
  140. for i in range(len(line)):
  141. if record[i]:
  142. to_write.append(line[i])
  143. f_csv.writerow(to_write)
  144. f.close()
  145. def write_to_excel(file_name, data, types, record):
  146. first = False
  147. if os.path.exists(file_name):
  148. # 加载现有的工作簿
  149. wb = load_workbook(file_name)
  150. ws = wb.active
  151. else:
  152. # 创建新的工作簿和工作表
  153. wb = Workbook()
  154. ws = wb.active
  155. first = True
  156. # 追加数据到工作表
  157. for line in data:
  158. if not first: # 如果不是第一行,需要转换数据类型
  159. for i in range(len(line)):
  160. if types[i] == "int" or types[i] == "bigInt":
  161. try:
  162. line[i] = int(line[i])
  163. except:
  164. line[i] = 0
  165. elif types[i] == "double":
  166. try:
  167. line[i] = float(line[i])
  168. except:
  169. line[i] = 0.0
  170. else:
  171. first = False
  172. to_write = []
  173. for i in range(len(line)):
  174. if record[i]:
  175. to_write.append(line[i])
  176. ws.append(to_write)
  177. # 保存工作簿
  178. wb.save(file_name)
  179. class Time:
  180. def __init__(self, type1=""):
  181. self.t = int(round(time.time() * 1000))
  182. self.type = type1
  183. def end(self):
  184. at = int(round(time.time() * 1000))
  185. print("Time used for", self.type, ":", at - self.t, "ms")
  186. class myMySQL:
  187. def __init__(self, config_file="mysql_config.json"):
  188. # 读取配置文件
  189. try:
  190. with open(config_file, 'r') as f:
  191. config = json.load(f)
  192. host = config["host"]
  193. port = config["port"]
  194. user = config["user"]
  195. passwd = config["password"]
  196. db = config["database"]
  197. except:
  198. print("读取配置文件失败,请检查配置文件:"+config_file+"是否存在。")
  199. print("Failed to read configuration file, please check if the configuration file: "+config_file+" exists.")
  200. try:
  201. self.conn = pymysql.connect(
  202. host=host, port=port, user=user, passwd=passwd, db=db)
  203. print("成功连接到数据库。")
  204. print("Successfully connected to the database.")
  205. except:
  206. print("连接数据库失败,请检查配置文件是否正确。")
  207. print("Failed to connect to the database, please check if the configuration file is correct.")
  208. def create_table(self, table_name, parameters):
  209. self.table_name = table_name
  210. self.field_sql = "("
  211. cursor = self.conn.cursor()
  212. # 检查表是否存在
  213. cursor.execute("SHOW TABLES LIKE '%s'" % table_name)
  214. result = cursor.fetchone()
  215. sql = "CREATE TABLE " + table_name + " (_id INT AUTO_INCREMENT PRIMARY KEY, "
  216. for item in parameters:
  217. if item["recordASField"]:
  218. name = item['name']
  219. if item['type'] == 'int':
  220. sql += f"{name} INT, "
  221. elif item['type'] == 'double':
  222. sql += f"{name} DOUBLE, "
  223. elif item['type'] == 'text':
  224. sql += f"{name} TEXT, "
  225. elif item['type'] == 'mediumText':
  226. sql += f"{name} MEDIUMTEXT, "
  227. elif item['type'] == 'longText':
  228. sql += f"{name} LONGTEXT, "
  229. elif item['type'] == 'datetime':
  230. sql += f"{name} DATETIME, "
  231. elif item['type'] == 'date':
  232. sql += f"{name} DATE, "
  233. elif item['type'] == 'time':
  234. sql += f"{name} TIME, "
  235. elif item['type'] == 'varchar':
  236. sql += f"{name} VARCHAR(255), "
  237. elif item['type'] == 'bigInt':
  238. sql += f"{name} BIGINT, "
  239. self.field_sql += f"{name}, "
  240. # 移除最后的逗号并添加闭合的括号
  241. sql = sql.rstrip(', ') + ")"
  242. self.field_sql = self.field_sql.rstrip(', ') + ")"
  243. # 如果表不存在,创建它
  244. if not result:
  245. # 执行SQL命令
  246. cursor.execute(sql)
  247. else:
  248. print("数据表" + table_name + "已存在。")
  249. print("The data table " + table_name + " already exists.")
  250. cursor.close()
  251. def write_to_mysql(self, OUTPUT, record, types):
  252. # 创建一个游标对象
  253. cursor = self.conn.cursor()
  254. for line in OUTPUT:
  255. for i in range(len(line)):
  256. if types[i] == "int" or types[i] == "bigInt":
  257. try:
  258. line[i] = int(line[i])
  259. except:
  260. line[i] = 0
  261. elif types[i] == "double":
  262. try:
  263. line[i] = float(line[i])
  264. except:
  265. line[i] = 0.0
  266. elif types[i] == "datetime":
  267. try:
  268. line[i] = datetime.datetime.strptime(line[i], '%Y-%m-%d %H:%M:%S')
  269. except:
  270. line[i] = datetime.datetime.strptime("1970-01-01 00:00:00", '%Y-%m-%d %H:%M:%S')
  271. elif types[i] == "date":
  272. try:
  273. line[i] = datetime.datetime.strptime(line[i], '%Y-%m-%d')
  274. except:
  275. line[i] = datetime.datetime.strptime("1970-01-01", '%Y-%m-%d')
  276. elif types[i] == "time":
  277. try:
  278. line[i] = datetime.datetime.strptime(line[i], '%H:%M:%S')
  279. except:
  280. line[i] = datetime.datetime.strptime("00:00:00", '%H:%M:%S')
  281. to_write = []
  282. for i in range(len(line)):
  283. if record[i]:
  284. to_write.append(line[i])
  285. # 构造插入数据的 SQL 语句
  286. sql = f"INSERT INTO "+ self.table_name +" "+self.field_sql+" VALUES ("
  287. for item in to_write:
  288. sql += "%s, "
  289. # 移除最后的逗号并添加闭合的括号
  290. sql = sql.rstrip(', ') + ")"
  291. # 执行 SQL 语句
  292. try:
  293. cursor.execute(sql, to_write)
  294. except Exception as e:
  295. print("Error:", e)
  296. print("Error SQL:", sql, to_write)
  297. print("插入数据库错误,请查看以上的错误提示,然后检查数据的类型是否正确,是否文本过长(超过一万的文本类型要设置为大文本)。")
  298. print("Inserting database error, please check the above error, and then check whether the data type is correct, whether the text is too long (text type over 10,000 should be set to large text).")
  299. print("重新执行任务时,请删除数据库中的数据表" + self.table_name + ",然后再次运行程序。")
  300. print("When re-executing the task, please delete the data table " + self.table_name + " in the database, and then run the program again.")
  301. # 提交到数据库执行
  302. self.conn.commit()
  303. # 关闭游标和连接
  304. cursor.close()
  305. def close(self):
  306. self.conn.close()
  307. print("成功关闭数据库。")
  308. print("Successfully closed the database.")