easyspider_executestage.py 98 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885
  1. # -*- coding: utf-8 -*-
  2. # import atexit
  3. from datetime import datetime
  4. import io # 遇到错误退出时应执行的代码
  5. import json
  6. # from lib2to3.pgen2 import driver
  7. import re
  8. # import shutil
  9. import subprocess
  10. import sys
  11. # from urllib import parse
  12. # import base64
  13. # import hashlib
  14. import time
  15. import requests
  16. from ddddocr import DdddOcr
  17. from urllib.parse import urljoin
  18. from lxml import etree
  19. import onnxruntime
  20. onnxruntime.set_default_logger_severity(3) # 隐藏onnxruntime的日志
  21. # import undetected_chromedriver as uc
  22. from pynput.keyboard import Key, Listener
  23. from selenium.webdriver.chrome.options import Options
  24. from selenium.webdriver.common.keys import Keys
  25. from selenium.webdriver.common.action_chains import ActionChains
  26. from selenium import webdriver
  27. from selenium.webdriver.support.ui import WebDriverWait
  28. from selenium.webdriver.support import expected_conditions as EC
  29. from selenium.webdriver.common.by import By
  30. from selenium.common.exceptions import NoSuchElementException
  31. from selenium.common.exceptions import TimeoutException
  32. from selenium.common.exceptions import StaleElementReferenceException, InvalidSelectorException
  33. from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
  34. from selenium.webdriver.support.ui import Select
  35. from selenium.webdriver import ActionChains
  36. from selenium.webdriver.common.by import By
  37. import random
  38. # import pandas as pd
  39. from openpyxl import load_workbook, Workbook
  40. # import numpy
  41. import csv
  42. import os
  43. from commandline_config import Config
  44. # import pytesseract
  45. from PIL import Image
  46. # import uuid
  47. from threading import Thread, Event
  48. from myChrome import MyChrome
  49. if sys.platform != "darwin":
  50. from myChrome import MyUCChrome
  51. from utils import download_image, get_output_code, isnotnull, lowercase_tags_in_xpath, myMySQL, new_line, on_press_creator, on_release_creator, replace_field_values, write_to_csv, write_to_excel
  52. desired_capabilities = DesiredCapabilities.CHROME
  53. desired_capabilities["pageLoadStrategy"] = "none"
  54. class BrowserThread(Thread):
  55. def __init__(self, browser_t, id, service, version, event, saveName, config):
  56. Thread.__init__(self)
  57. self.browser = browser_t
  58. self.config = config
  59. self.version = version
  60. self.totalSteps = 0
  61. self.id = id
  62. self.event = event
  63. try:
  64. self.saveName = service["saveName"] # 保存文件的名字
  65. except:
  66. now = datetime.now()
  67. # 将时间格式化为精确到秒的字符串
  68. self.saveName = now.strftime("%Y_%m_%d_%H_%M_%S")
  69. self.log = ""
  70. self.OUTPUT = ""
  71. self.SAVED = False
  72. self.BREAK = False
  73. self.CONTINUE = False
  74. # 名称设定
  75. if saveName != "": # 命令行覆盖保存名称
  76. self.saveName = saveName # 保存文件的名字
  77. now = datetime.now().strftime("%Y_%m_%d_%H_%M_%S")
  78. self.saveName = self.saveName.replace("current_time", now)
  79. print("Save Name for task ID", i, "is:", self.saveName)
  80. print("任务ID", i, "的保存文件名为:", self.saveName)
  81. if not os.path.exists("Data/Task_" + str(i)):
  82. os.mkdir("Data/Task_" + str(i))
  83. if not os.path.exists("Data/Task_" + str(i) + "/" + self.saveName):
  84. os.mkdir("Data/Task_" + str(i) + "/" + self.saveName) # 创建保存文件夹用来保存截图
  85. self.getDataStep = 0
  86. self.startSteps = 0
  87. try:
  88. startFromExit = service["startFromExit"] # 从上次退出的步骤开始
  89. if startFromExit == 1:
  90. with open("Data/Task_" + str(self.id) + "/" + self.saveName + '_steps.txt', 'r', encoding='utf-8-sig') as file_obj:
  91. self.startSteps = int(file_obj.read()) # 读取已执行步数
  92. except:
  93. pass
  94. if self.startSteps != 0:
  95. print("此模式下,任务ID", self.id, "将从上次退出的步骤开始执行,之前已采集条数为", self.startSteps, "条。")
  96. print("In this mode, task ID", self.id, "will start from the last step, before we already collected", self.startSteps, " items.")
  97. else:
  98. print("此模式下,任务ID", self.id, "将从头开始执行,如果需要从上次退出的步骤开始执行,请在保存任务时设置是否从上次保存位置开始执行为“是”。")
  99. print("In this mode, task ID", self.id, "will start from the beginning, if you want to start from the last step, please set the option 'start from the last step' to 'yes' when saving the task.")
  100. stealth_path = driver_path[:driver_path.find(
  101. "chromedriver")] + "stealth.min.js"
  102. with open(stealth_path, 'r') as f:
  103. js = f.read()
  104. print("Loading stealth.min.js")
  105. self.browser.execute_cdp_cmd('Page.addScriptToEvaluateOnNewDocument', {
  106. 'source': js}) # TMALL 反扒
  107. WebDriverWait(self.browser, 10)
  108. self.browser.get('about:blank')
  109. self.procedure = service["graph"] # 程序执行流程
  110. try:
  111. self.maxViewLength = service["maxViewLength"] # 最大显示长度
  112. except:
  113. self.maxViewLength = 15
  114. try:
  115. self.outputFormat = service["outputFormat"] # 输出格式
  116. except:
  117. self.outputFormat = "csv"
  118. try:
  119. self.task_version = service["version"] # 任务版本
  120. if service["version"] >= "0.3.1": # 0.3.1及以上版本以上的EasySpider兼容从0.3.1版本开始的所有版本
  121. pass
  122. else: # 0.3.1以下版本的EasySpider不兼容0.3.1及以上版本的EasySpider
  123. if service["version"] != version:
  124. print("版本不一致,请使用" +
  125. service["version"] + "版本的EasySpider运行该任务!")
  126. print("Version not match, please use EasySpider " +
  127. service["version"] + " to run this task!")
  128. self.browser.quit()
  129. sys.exit()
  130. except: # 0.2.0版本没有version字段,所以直接退出
  131. print("版本不一致,请使用v0.2.0版本的EasySpider运行该任务!")
  132. print("Version not match, please use EasySpider v0.2.0 to run this task!")
  133. self.browser.quit()
  134. sys.exit()
  135. try:
  136. self.save_threshold = service["saveThreshold"] # 保存最低阈值
  137. except:
  138. self.save_threshold = 10
  139. self.links = list(
  140. filter(isnotnull, service["links"].split("\n"))) # 要执行的link的列表
  141. self.OUTPUT = [] # 采集的数据
  142. self.writeMode = 1 # 写入模式,0为新建,1为追加
  143. if self.outputFormat == "csv" or self.outputFormat == "txt":
  144. if not os.path.exists("Data/Task_" + str(self.id) + "/" + self.saveName + '.' + self.outputFormat):
  145. self.OUTPUT.append([]) # 添加表头
  146. self.writeMode = 0
  147. elif self.outputFormat == "xlsx":
  148. if not os.path.exists("Data/Task_" + str(self.id) + "/" + self.saveName + '.xlsx'):
  149. self.OUTPUT.append([]) # 添加表头
  150. self.writeMode = 0
  151. elif self.outputFormat == "mysql":
  152. self.mysql = myMySQL(config["mysql_config_path"])
  153. self.mysql.create_table(self.saveName, service["outputParameters"])
  154. self.writeMode = 2
  155. if self.writeMode == 1:
  156. print("追加模式")
  157. print("Append Mode")
  158. elif self.writeMode == 0:
  159. print("新建模式")
  160. print("New Mode")
  161. elif self.writeMode == 2:
  162. print("MySQL模式")
  163. print("MySQL Mode")
  164. self.containJudge = service["containJudge"] # 是否含有判断语句
  165. self.outputParameters = {}
  166. self.service = service
  167. self.outputParametersTypes = []
  168. self.outputParametersRecord = [] # 字段是否被记录
  169. self.dataNotFoundKeys = {} # 记录没有找到数据的key
  170. self.log = "" # 记下现在总共开了多少个标签页
  171. self.history = {"index": 0, "handle": None} # 记录页面现在所以在的历史记录的位置
  172. self.SAVED = False # 记录是否已经存储了
  173. for para in service["outputParameters"]: # 初始化输出参数
  174. if para["name"] not in self.outputParameters.keys():
  175. self.outputParameters[para["name"]] = ""
  176. self.dataNotFoundKeys[para["name"]] = False
  177. try:
  178. self.outputParametersTypes.append(para["type"])
  179. except:
  180. self.outputParametersTypes.append("text")
  181. try:
  182. self.outputParametersRecord.append(bool(para["recordASField"]))
  183. except:
  184. self.outputParametersRecord.append(True)
  185. # 文件叠加的时候不添加表头
  186. if self.outputFormat == "csv" or self.outputFormat == "txt" or self.outputFormat == "xlsx":
  187. if self.writeMode == 0:
  188. self.OUTPUT[0].append(para["name"])
  189. self.urlId = 0 # 全局记录变量
  190. self.preprocess() # 预处理,优化提取数据流程
  191. try:
  192. self.inputExcel = service["inputExcel"] # 输入Excel
  193. except:
  194. self.inputExcel = ""
  195. self.readFromExcel() # 读取Excel获得参数值
  196. # 检测如果没有复杂的操作,优化提取数据流程
  197. def preprocess(self):
  198. for node in self.procedure:
  199. try:
  200. iframe = node["parameters"]["iframe"]
  201. except:
  202. node["parameters"]["iframe"] = False
  203. try:
  204. node["parameters"]["xpath"] = lowercase_tags_in_xpath(
  205. node["parameters"]["xpath"])
  206. except:
  207. pass
  208. if node["option"] == 1: # 打开网页操作
  209. try:
  210. cookies = node["parameters"]["cookies"]
  211. except:
  212. node["parameters"]["cookies"] = ""
  213. if node["option"] == 2: # 点击操作
  214. if node["parameters"]["useLoop"]:
  215. if self.task_version <= "0.3.5":
  216. node["parameters"]["xpath"] = "" # 0.3.5及以下版本的EasySpider下的循环点击不支持相对XPath
  217. print("您的任务版本号为" + self.task_version + ",循环点击不支持相对XPath写法,已自动切换为纯循环的XPath")
  218. elif node["option"] == 3: # 提取数据操作
  219. node["parameters"]["recordASField"] = 0
  220. paras = node["parameters"]["paras"]
  221. try:
  222. clear = node["parameters"]["clear"]
  223. except:
  224. node["parameters"]["clear"] = 0
  225. for para in paras:
  226. try:
  227. iframe = para["iframe"]
  228. except:
  229. para["iframe"] = False
  230. try:
  231. para["relativeXPath"] = lowercase_tags_in_xpath(para["relativeXPath"])
  232. except:
  233. pass
  234. try:
  235. node["parameters"]["recordASField"] += para["recordASField"]
  236. except:
  237. node["parameters"]["recordASField"] += 1
  238. if para["contentType"] == 8:
  239. print("默认的ddddocr识别功能如果觉得不好用,可以自行修改源码get_content函数->contentType == 8的位置换成自己想要的OCR模型然后自己编译运行;或者可以先设置采集内容类型为“元素截图”把图片保存下来,然后用自定义操作调用自己写的程序,程序的功能是读取这个最新生成的图片,然后用好用的模型,如PaddleOCR把图片识别出来,然后把返回值返回给程序作为参数输出。")
  240. print("If you think the default ddddocr function is not good enough, you can modify the source code get_content function -> contentType == 8 position to your own OCR model and then compile and run it; or you can first set the content type of the crawler to \"Element Screenshot\" to save the picture, and then call your own program with custom operations. The function of the program is to read the latest generated picture, then use a good model, such as PaddleOCR to recognize the picture, and then return the return value as a parameter output to the program.")
  241. if para["beforeJS"] == "" and para["afterJS"] == "" and para["contentType"] <= 1 and para["nodeType"] <= 2:
  242. para["optimizable"] = True
  243. else:
  244. para["optimizable"] = False
  245. elif node["option"] == 4: # 输入文字
  246. try:
  247. index = node["parameters"]["index"] # 索引值
  248. except:
  249. node["parameters"]["index"] = 0
  250. elif node["option"] == 5: # 自定义操作
  251. try:
  252. clear = node["parameters"]["clear"]
  253. except:
  254. node["parameters"]["clear"] = 0
  255. elif node["option"] == 7: # 移动到元素
  256. if node["parameters"]["useLoop"]:
  257. if self.task_version <= "0.3.5":
  258. node["parameters"]["xpath"] = "" # 0.3.5及以下版本的EasySpider下的循环点击不支持相对XPath
  259. print("您的任务版本号为" + self.task_version + ",循环点击不支持相对XPath写法,已自动切换为纯循环的XPath")
  260. def readFromExcel(self):
  261. if self.inputExcel == "":
  262. return 0
  263. try:
  264. workbook = load_workbook(self.inputExcel)
  265. except:
  266. print("读取Excel失败,将会使用默认参数执行任务,请检查文件路径是否正确:", os.path.abspath(self.inputExcel))
  267. print("Failed to read Excel, will execute the task with default parameters, please check if the file path is correct: ", os.path.abspath(self.inputExcel))
  268. time.sleep(5)
  269. return 0
  270. sheet_name_list = workbook.sheetnames
  271. sheet = workbook[sheet_name_list[0]]
  272. data = []
  273. for row in sheet.iter_rows(values_only=True):
  274. data.append(list(row))
  275. result = list(zip(*data))
  276. result_dict = {}
  277. for row in result:
  278. key = row[0]
  279. values = [str(val) for val in row[1:] if val is not None]
  280. result_dict.setdefault(key, []).extend([values])
  281. data = {}
  282. for key, arr in result_dict.items():
  283. result = []
  284. for cols in zip(*arr):
  285. result.append("~".join(cols))
  286. data[key] = result
  287. try:
  288. if "urlList_0" in data.keys():
  289. self.links = data["urlList_0"]
  290. except:
  291. pass
  292. task = self.service
  293. for key, value in data.items():
  294. for i in range(len(task["inputParameters"])):
  295. if key == task["inputParameters"][i]["name"]:
  296. nodeId = int(task["inputParameters"][i]["nodeId"])
  297. node = task["graph"][nodeId]
  298. value = "\r\n".join(value)
  299. if node["option"] == 1:
  300. node["parameters"]["links"] = value
  301. elif node["option"] == 4:
  302. node["parameters"]["value"] = value
  303. elif node["option"] == 8 and node["parameters"]["loopType"] == 0:
  304. node["parameters"]["exitCount"] = int(value)
  305. elif node["option"] == 8:
  306. node["parameters"]["textList"] = value
  307. break
  308. print("已从Excel读取输入参数,覆盖了原有输入参数。")
  309. print("Alread read input parameters from Excel and overwrite the original input parameters.")
  310. def run(self):
  311. # 挨个执行程序
  312. for i in range(len(self.links)):
  313. print("正在执行第", i + 1, "/ ", len(self.links), "个链接")
  314. print("Executing link", i + 1, "/ ", len(self.links))
  315. self.executeNode(0)
  316. self.urlId = self.urlId + 1
  317. files = os.listdir("Data/Task_" + str(self.id) + "/" + self.saveName)
  318. # 如果目录为空,则删除该目录
  319. if not files:
  320. os.rmdir("Data/Task_" + str(self.id) + "/" + self.saveName)
  321. print("Done!")
  322. print("执行完成!")
  323. self.recordLog("Done!")
  324. self.saveData(exit=True)
  325. if self.outputFormat == "mysql":
  326. self.mysql.close()
  327. def recordLog(self, str=""):
  328. self.log = self.log + str + "\n"
  329. # 控制台打印log函数
  330. def Log(self, text, text2=""):
  331. switch = False
  332. if switch:
  333. print(text, text2)
  334. # @atexit.register
  335. # def clean(self):
  336. # self.saveData(exit=True)
  337. # self.browser.quit()
  338. # sys.exit(0)
  339. def saveData(self, exit=False):
  340. # 每save_threshold条保存一次
  341. if exit == True or len(self.OUTPUT) >= self.save_threshold:
  342. # 写入日志
  343. with open("Data/Task_" + str(self.id) + "/" + self.saveName + '_log.txt', 'a', encoding='utf-8-sig') as file_obj:
  344. file_obj.write(self.log)
  345. file_obj.close()
  346. # 写入已执行步数
  347. with open("Data/Task_" + str(self.id) + "/" + self.saveName + '_steps.txt', 'w', encoding='utf-8-sig') as file_obj:
  348. file_obj.write(str(self.totalSteps + 1))
  349. file_obj.close()
  350. # 写入数据
  351. if self.outputFormat == "csv" or self.outputFormat == "txt":
  352. file_name = "Data/Task_" + \
  353. str(self.id) + "/" + self.saveName + '.' + self.outputFormat
  354. write_to_csv(file_name, self.OUTPUT, self.outputParametersRecord)
  355. elif self.outputFormat == "xlsx":
  356. file_name = "Data/Task_" + \
  357. str(self.id) + "/" + self.saveName + '.xlsx'
  358. write_to_excel(file_name, self.OUTPUT, self.outputParametersTypes, self.outputParametersRecord)
  359. elif self.outputFormat == "mysql":
  360. self.mysql.write_to_mysql(self.OUTPUT, self.outputParametersRecord, self.outputParametersTypes)
  361. self.OUTPUT = []
  362. self.log = ""
  363. def scrollDown(self, para, rt=""):
  364. try:
  365. time.sleep(para["scrollWaitTime"]) # 下拉前等待
  366. except:
  367. pass
  368. scrollType = int(para["scrollType"])
  369. try:
  370. if scrollType != 0 and para["scrollCount"] > 0: # 控制屏幕向下滚动
  371. if scrollType == 1 or scrollType == 2:
  372. for i in range(para["scrollCount"]):
  373. self.Log("Wait for set second after screen scrolling")
  374. body = self.browser.find_element(
  375. By.CSS_SELECTOR, "body", iframe=para["iframe"])
  376. if scrollType == 1:
  377. body.send_keys(Keys.PAGE_DOWN)
  378. elif scrollType == 2:
  379. body.send_keys(Keys.END)
  380. try:
  381. time.sleep(para["scrollWaitTime"]) # 下拉完等待
  382. except:
  383. pass
  384. elif scrollType == 3:
  385. bodyText = ""
  386. i = 0
  387. while True:
  388. # newBodyText = self.browser.page_source
  389. newBodyText = self.browser.find_element(By.CSS_SELECTOR, "body", iframe=para["iframe"]).text
  390. if newBodyText == bodyText:
  391. print("页面已检测不到新内容,停止滚动。")
  392. print("No new content detected on the page, stop scrolling.")
  393. break
  394. else:
  395. bodyText = newBodyText
  396. body = self.browser.find_element(
  397. By.CSS_SELECTOR, "body", iframe=para["iframe"])
  398. body.send_keys(Keys.END)
  399. print("滚动到底部,第", i + 1, "次。")
  400. print("Scroll to the bottom, the", i + 1, "time.")
  401. i = i + 1
  402. try:
  403. time.sleep(para["scrollWaitTime"]) # 下拉完等待
  404. except:
  405. pass
  406. except:
  407. self.Log('Time out after set seconds when scrolling. ')
  408. self.recordLog('Time out after set seconds when scrolling')
  409. try:
  410. self.browser.execute_script('window.stop()')
  411. except:
  412. pass
  413. if scrollType != 0 and para["scrollCount"] > 0: # 控制屏幕向下滚动
  414. for i in range(para["scrollCount"]):
  415. self.Log("Wait for set second after screen scrolling")
  416. body = self.browser.find_element(
  417. By.CSS_SELECTOR, "body", iframe=para["iframe"])
  418. if scrollType == 1:
  419. body.send_keys(Keys.PGDN)
  420. elif scrollType == 2:
  421. body.send_keys(Keys.END)
  422. try:
  423. time.sleep(para["scrollWaitTime"]) # 下拉完等待
  424. except:
  425. pass
  426. if rt != "":
  427. rt.end()
  428. def execute_code(self, codeMode, code, max_wait_time, element=None, iframe=False):
  429. output = ""
  430. if code == "":
  431. return ""
  432. if max_wait_time == 0:
  433. max_wait_time = 999999
  434. # print(codeMode, code)
  435. # 将value中的Field[""]替换为outputParameters中的键值
  436. code = replace_field_values(code, self.outputParameters)
  437. if iframe and self.browser.iframe_env == False:
  438. # 获取所有的 iframe
  439. self.browser.switch_to.default_content()
  440. iframes = self.browser.find_elements(
  441. By.CSS_SELECTOR, "iframe", iframe=False)
  442. # 遍历所有的 iframe 并点击里面的元素
  443. for iframe in iframes:
  444. # 切换到 iframe
  445. try:
  446. self.browser.switch_to.default_content()
  447. self.browser.switch_to.frame(iframe)
  448. self.browser.iframe_env = True
  449. break
  450. except:
  451. print("Iframe switch failed")
  452. elif not iframe and self.browser.iframe_env == True:
  453. self.browser.switch_to.default_content()
  454. self.browser.iframe_env = False
  455. if int(codeMode) == 0:
  456. self.recordLog("Execute JavaScript:" + code)
  457. self.recordLog("执行JavaScript:" + code)
  458. self.browser.set_script_timeout(max_wait_time)
  459. try:
  460. output = self.browser.execute_script(code)
  461. except:
  462. output = ""
  463. self.recordLog("JavaScript execution failed")
  464. elif int(codeMode) == 2:
  465. self.recordLog("Execute JavaScript for element:" + code)
  466. self.recordLog("对元素执行JavaScript:" + code)
  467. self.browser.set_script_timeout(max_wait_time)
  468. try:
  469. output = self.browser.execute_script(code, element)
  470. except:
  471. output = ""
  472. self.recordLog("JavaScript execution failed")
  473. elif int(codeMode) == 5:
  474. try:
  475. output = exec(code)
  476. except Exception as e:
  477. print("执行下面的代码时出错:" + code, ",错误为:", e)
  478. print("Error executing the following code:" + code, ", error is:", e)
  479. elif int(codeMode) == 6:
  480. try:
  481. output = eval(code)
  482. except Exception as e:
  483. print("获得下面的代码返回值时出错:" + code, ",错误为:", e)
  484. print("Error executing and getting return value the following code:" + code, ", error is:", e)
  485. elif int(codeMode) == 1:
  486. self.recordLog("Execute System Call:" + code)
  487. self.recordLog("执行系统命令:" + code)
  488. # 执行系统命令
  489. try:
  490. # output = subprocess.run(code, capture_output=True, text=True, timeout=max_wait_time, encoding="utf-8", shell=True)
  491. output = subprocess.run(
  492. code, capture_output=True, text=True, timeout=max_wait_time, shell=True)
  493. # 输出命令返回值
  494. output = output.stdout
  495. print(output)
  496. except subprocess.TimeoutExpired:
  497. # 命令执行时间超过指定值,抛出异常
  498. self.recordLog("Command timed out")
  499. self.recordLog("命令执行超时")
  500. except Exception as e:
  501. print(e) # 打印异常信息
  502. self.recordLog("Command execution failed")
  503. self.recordLog("命令执行失败")
  504. return str(output)
  505. def customOperation(self, node, loopValue, loopPath, index):
  506. paras = node["parameters"]
  507. if paras["clear"] == 1:
  508. self.clearOutputParameters()
  509. codeMode = int(paras["codeMode"])
  510. code = paras["code"]
  511. output = ""
  512. max_wait_time = int(paras["waitTime"])
  513. if codeMode == 2: # 使用循环的情况下,传入的clickPath就是实际的xpath
  514. try:
  515. loopPath = replace_field_values(loopPath, self.outputParameters)
  516. elements = self.browser.find_elements(
  517. By.XPATH, loopPath, iframe=paras["iframe"])
  518. element = elements[index]
  519. output = self.execute_code(
  520. codeMode, code, max_wait_time, element, iframe=paras["iframe"])
  521. except:
  522. output = ""
  523. print("JavaScript execution failed")
  524. elif codeMode == 3:
  525. self.BREAK = True
  526. elif codeMode == 4:
  527. self.CONTINUE = True
  528. else: # 0 1 5 6
  529. output = self.execute_code(
  530. codeMode, code, max_wait_time, iframe=paras["iframe"])
  531. recordASField = bool(paras["recordASField"])
  532. # if recordASField:
  533. # print("操作<" + node["title"] + ">的返回值为:" + output)
  534. # print("The return value of operation <" + node["title"] + "> is: " + output)
  535. self.outputParameters[node["title"]] = output
  536. if recordASField:
  537. line = new_line(self.outputParameters, self.maxViewLength, self.outputParametersRecord)
  538. self.OUTPUT.append(line)
  539. def switchSelect(self, para, loopValue):
  540. optionMode = para["optionMode"]
  541. optionValue = para["optionValue"]
  542. if para["useLoop"]:
  543. index = para["index"]
  544. if index != 0:
  545. try:
  546. optionValue = loopValue.split("~")[index - 1]
  547. except:
  548. print("取值失败,可能是因为取值索引超出范围,将使用整个文本值")
  549. print("Failed to get value, maybe because the index is out of range, will use the entire text value")
  550. else:
  551. optionValue = loopValue
  552. optionMode = 1
  553. try:
  554. xpath = replace_field_values(para["xpath"], self.outputParameters)
  555. dropdown = Select(self.browser.find_element(
  556. By.XPATH, xpath, iframe=para["iframe"]))
  557. try:
  558. if optionMode == 0:
  559. # 获取当前选中的选项索引
  560. current_index = dropdown.options.index(
  561. dropdown.first_selected_option)
  562. # 计算下一个选项的索引
  563. next_index = (current_index + 1) % len(dropdown.options)
  564. # 选择下一个选项
  565. dropdown.select_by_index(next_index)
  566. elif optionMode == 1:
  567. dropdown.select_by_index(int(optionValue))
  568. elif optionMode == 2:
  569. dropdown.select_by_value(optionValue)
  570. elif optionMode == 3:
  571. dropdown.select_by_visible_text(optionValue)
  572. except:
  573. print("切换下拉框选项失败:", xpath,
  574. para["optionMode"], para["optionValue"])
  575. print("Failed to change drop-down box option:",
  576. xpath, para["optionMode"], para["optionValue"])
  577. except:
  578. print("找不到下拉框元素:", xpath)
  579. print("Cannot find drop-down box element:", xpath)
  580. def moveToElement(self, para, loopElement=None, loopPath="", index=0):
  581. time.sleep(0.1) # 移动之前等待0.1秒
  582. loopPath = replace_field_values(loopPath, self.outputParameters)
  583. xpath = replace_field_values(para["xpath"], self.outputParameters)
  584. if para["useLoop"]: # 使用循环的情况下,传入的clickPath就是实际的xpath
  585. if xpath == "":
  586. path = loopPath
  587. else:
  588. path = "(" + loopPath + ")" + \
  589. "[" + str(index + 1) + "]" + \
  590. xpath
  591. index = 0 # 如果是相对循环内元素的点击,在定位到元素后,index应该重置为0
  592. # element = loopElement
  593. else:
  594. index = 0
  595. path = xpath # 不然使用元素定义的xpath
  596. path = replace_field_values(path, self.outputParameters)
  597. try:
  598. elements = self.browser.find_elements(
  599. By.XPATH, path, iframe=para["iframe"])
  600. element = elements[index]
  601. try:
  602. ActionChains(self.browser).move_to_element(element).perform()
  603. except:
  604. print("移动鼠标到元素失败:", xpath)
  605. print("Failed to move mouse to element:", xpath)
  606. except:
  607. print("找不到元素:", xpath)
  608. print("Cannot find element:", xpath)
  609. # 执行节点关键函数部分
  610. def executeNode(self, nodeId, loopValue="", loopPath="", index=0):
  611. node = self.procedure[nodeId]
  612. WebDriverWait(self.browser, 10).until
  613. # 等待元素出现才进行操作,10秒内未出现则报错
  614. (EC.visibility_of_element_located(
  615. (By.XPATH, node["parameters"]["xpath"])))
  616. # 根据不同选项执行不同操作
  617. if node["option"] == 0 or node["option"] == 10: # root操作,条件分支操作
  618. for i in node["sequence"]: # 从根节点开始向下读取
  619. self.executeNode(i, loopValue, loopPath, index)
  620. elif node["option"] == 1: # 打开网页操作
  621. self.recordLog("openPage")
  622. self.openPage(node["parameters"], loopValue)
  623. elif node["option"] == 2: # 点击元素
  624. self.recordLog("Click")
  625. self.clickElement(node["parameters"], loopValue, loopPath, index)
  626. elif node["option"] == 3: # 提取数据
  627. # 针对提取数据操作,设置操作开始的步骤,用于不小心关闭后的恢复的增量采集
  628. if self.totalSteps >= self.startSteps:
  629. self.recordLog("getData")
  630. self.getData(node["parameters"], loopValue, node["isInLoop"],
  631. parentPath=loopPath, index=index)
  632. self.saveData()
  633. else:
  634. # self.getDataStep += 1
  635. print("跳过第" + str(self.totalSteps) + "次提取数据。")
  636. print("Skip the " + str(self.totalSteps) + "th data extraction.")
  637. self.totalSteps += 1 # 总步数加一
  638. elif node["option"] == 4: # 输入文字
  639. self.inputInfo(node["parameters"], loopValue)
  640. elif node["option"] == 5: # 自定义操作
  641. self.customOperation(node, loopValue, loopPath, index)
  642. self.saveData()
  643. elif node["option"] == 6: # 切换下拉框
  644. self.switchSelect(node["parameters"], loopValue)
  645. elif node["option"] == 7: # 鼠标移动到元素上
  646. self.moveToElement(node["parameters"], loopValue, loopPath, index)
  647. elif node["option"] == 8: # 循环
  648. self.recordLog("loop")
  649. self.loopExecute(node, loopValue, loopPath, index) # 执行循环
  650. elif node["option"] == 9: # 条件分支
  651. self.recordLog("judge")
  652. self.judgeExecute(node, loopValue, loopPath, index)
  653. # 执行完之后进行等待
  654. if node["option"] != 0 and node["option"] != 2: # 点击元素操作单独定义等待时间操作
  655. waitTime = 0.01 # 默认等待0.01秒
  656. if node["parameters"]["wait"] >= 0:
  657. waitTime = node["parameters"]["wait"]
  658. try:
  659. waitType = int(node["parameters"]["waitType"])
  660. except:
  661. waitType = 0
  662. if waitType == 0: # 固定等待时间
  663. time.sleep(waitTime)
  664. elif waitType == 1: # 随机等待时间
  665. time.sleep(random.uniform(waitTime * 0.5, waitTime * 1.5))
  666. self.Log("Wait seconds after node executing: ", waitTime)
  667. self.event.wait() # 等待事件结束
  668. # 对判断条件的处理
  669. def judgeExecute(self, node, loopElement, clickPath="", index=0):
  670. executeBranchId = 0 # 要执行的BranchId
  671. for i in node["sequence"]:
  672. cnode = self.procedure[i] # 获得条件分支
  673. tType = int(cnode["parameters"]["class"]) # 获得判断条件类型
  674. if tType == 0: # 什么条件都没有
  675. executeBranchId = i
  676. break
  677. elif tType == 1: # 当前页面包含文本
  678. try:
  679. bodyText = self.browser.find_element(
  680. By.CSS_SELECTOR, "body", iframe=cnode["parameters"]["iframe"]).text
  681. value = replace_field_values(
  682. cnode["parameters"]["value"], self.outputParameters)
  683. if bodyText.find(value) >= 0:
  684. executeBranchId = i
  685. break
  686. except: # 找不到元素下一个条件
  687. continue
  688. elif tType == 2: # 当前页面包含元素
  689. try:
  690. xpath = replace_field_values(cnode["parameters"]["value"], self.outputParameters)
  691. if self.browser.find_element(By.XPATH, xpath, iframe=cnode["parameters"]["iframe"]):
  692. executeBranchId = i
  693. break
  694. except: # 找不到元素或者xpath写错了,下一个条件
  695. continue
  696. elif tType == 3: # 当前循环元素包括文本
  697. try:
  698. value = replace_field_values(cnode["parameters"]["value"], self.outputParameters)
  699. if loopElement.text.find(value) >= 0:
  700. executeBranchId = i
  701. break
  702. except: # 找不到元素或者xpath写错了,下一个条件
  703. continue
  704. elif tType == 4: # 当前循环元素包括元素
  705. try:
  706. xpath = replace_field_values(cnode["parameters"]["value"][1:], self.outputParameters)
  707. if loopElement.find_element(By.XPATH, xpath):
  708. executeBranchId = i
  709. break
  710. except: # 找不到元素或者xpath写错了,下一个条件
  711. continue
  712. elif tType <= 8: # JS命令返回值
  713. if tType == 5: # JS命令返回值等于
  714. output = self.execute_code(
  715. 0, cnode["parameters"]["code"], cnode["parameters"]["waitTime"], iframe=cnode["parameters"]["iframe"])
  716. elif tType == 6: # System
  717. output = self.execute_code(
  718. 1, cnode["parameters"]["code"], cnode["parameters"]["waitTime"], iframe=cnode["parameters"]["iframe"])
  719. elif tType == 7: # 针对当前循环项的JS命令返回值
  720. output = self.execute_code(
  721. 2, cnode["parameters"]["code"], cnode["parameters"]["waitTime"], loopElement, iframe=cnode["parameters"]["iframe"])
  722. elif tType == 8: # 针对当前循环项的System命令返回值
  723. output = self.execute_code(
  724. 6, cnode["parameters"]["code"], cnode["parameters"]["waitTime"], loopElement, iframe=cnode["parameters"]["iframe"])
  725. try:
  726. if output.find("rue") != -1: # 如果返回值中包含true
  727. code = 1
  728. else:
  729. code = int(output)
  730. except:
  731. code = 0
  732. if code > 0:
  733. executeBranchId = i
  734. break
  735. # rt.end()
  736. if executeBranchId != 0:
  737. self.executeNode(executeBranchId, loopElement, clickPath, index)
  738. # 对循环的处理
  739. def loopExecute(self, node, loopValue, clickPath="", index=0):
  740. time.sleep(0.1) # 第一次执行循环的时候强制等待1秒
  741. # self.Log("循环执行前等待0.1秒")
  742. self.Log("Wait 0.1 second before loop")
  743. thisHandle = self.browser.current_window_handle # 记录本次循环内的标签页的ID
  744. thisHistoryLength = self.browser.execute_script(
  745. 'return history.length') # 记录本次循环内的history的length
  746. self.history["index"] = thisHistoryLength
  747. self.history["handle"] = thisHandle
  748. if int(node["parameters"]["loopType"]) == 0: # 单个元素循环
  749. # 无跳转标签页操作
  750. count = 0 # 执行次数
  751. bodyText = "-"
  752. while True: # do while循环
  753. try:
  754. finished = False
  755. # newBodyText = self.browser.page_source
  756. # newBodyText = self.browser.find_element(By.XPATH, "//body").text
  757. newBodyText = self.browser.find_element(By.CSS_SELECTOR, "body", iframe=node["parameters"]["iframe"]).text
  758. if node["parameters"]["exitCount"] == 0:
  759. if newBodyText == bodyText: # 如果页面内容无变化
  760. print("页面已检测不到新内容,停止循环。")
  761. print("No new content detected on the page, stop loop.")
  762. finished = True
  763. break
  764. else:
  765. if node["parameters"]["exitCount"] == 0:
  766. print("检测到页面变化,继续循环。")
  767. print("Page changed detected, continue loop.")
  768. bodyText = newBodyText
  769. xpath = replace_field_values(
  770. node["parameters"]["xpath"], self.outputParameters)
  771. element = self.browser.find_element(
  772. By.XPATH, xpath, iframe=node["parameters"]["iframe"])
  773. for i in node["sequence"]: # 挨个执行操作
  774. self.executeNode(
  775. i, element, xpath, 0)
  776. if self.BREAK or self.CONTINUE: # 如果有break操作,下面的操作不执行
  777. self.CONTINUE = False
  778. break
  779. if self.BREAK: # 如果有break操作,退出循环
  780. self.BREAK = False
  781. finished = True
  782. break
  783. finished = True
  784. self.Log("Click: ", node["parameters"]["xpath"])
  785. self.recordLog("Click:" + node["parameters"]["xpath"])
  786. except NoSuchElementException:
  787. # except:
  788. print("Single loop element not found: ",
  789. xpath)
  790. print("找不到要循环的单个元素: ", xpath)
  791. self.recordLog(
  792. "Single loop element not found: " + node["parameters"]["xpath"])
  793. for i in node["sequence"]: # 不带点击元素的把剩余的如提取数据的操作执行一遍
  794. if node["option"] != 2:
  795. self.executeNode(
  796. i, None, xpath, 0)
  797. finished = True
  798. break # 如果找不到元素,退出循环
  799. finally:
  800. if not finished:
  801. print("\n\n-------Retrying-------\n\n")
  802. self.Log("-------Retrying-------: ",
  803. node["parameters"]["xpath"])
  804. self.recordLog("ClickNotFound:" +
  805. node["parameters"]["xpath"])
  806. for i in node["sequence"]: # 不带点击元素的把剩余的如提取数据的操作执行一遍
  807. if node["option"] != 2:
  808. self.executeNode(
  809. i, None, xpath, 0)
  810. break # 如果找不到元素,退出循环
  811. count = count + 1
  812. self.Log("Page: ", count)
  813. self.recordLog("Page:" + str(count))
  814. # print(node["parameters"]["exitCount"], "-------")
  815. if node["parameters"]["exitCount"] == count: # 如果达到设置的退出循环条件的话
  816. break
  817. if int(node["parameters"]["breakMode"]) > 0: # 如果设置了退出循环的脚本条件
  818. output = self.execute_code(int(
  819. node["parameters"]["breakMode"]) - 1, node["parameters"]["breakCode"], node["parameters"]["breakCodeWaitTime"], iframe=node["parameters"]["iframe"])
  820. code = get_output_code(output)
  821. if code <= 0:
  822. break
  823. elif int(node["parameters"]["loopType"]) == 1: # 不固定元素列表
  824. try:
  825. xpath = replace_field_values(
  826. node["parameters"]["xpath"], self.outputParameters)
  827. elements = self.browser.find_elements(By.XPATH,
  828. xpath, iframe=node["parameters"]["iframe"])
  829. if len(elements) == 0:
  830. print("Loop element not found: ",
  831. xpath)
  832. print("找不到循环元素: ", xpath)
  833. self.recordLog("pathNotFound: " +
  834. node["parameters"]["xpath"])
  835. for index in range(len(elements)):
  836. for i in node["sequence"]: # 挨个顺序执行循环里所有的操作
  837. self.executeNode(i, elements[index],
  838. xpath, index)
  839. if self.BREAK or self.CONTINUE: # 如果有break操作,下面的操作不执行
  840. self.CONTINUE = False
  841. break
  842. if self.BREAK:
  843. self.BREAK = False
  844. break
  845. try:
  846. changed_handle = self.browser.current_window_handle != thisHandle
  847. except: # 如果网页被意外关闭了的情况下
  848. self.browser.switch_to.window(
  849. self.browser.window_handles[-1])
  850. changed_handle = self.browser.window_handles[-1] != thisHandle
  851. if changed_handle: # 如果执行完一次循环之后标签页的位置发生了变化
  852. try:
  853. while True: # 一直关闭窗口直到当前标签页
  854. self.browser.close() # 关闭使用完的标签页
  855. self.browser.switch_to.window(
  856. self.browser.window_handles[-1])
  857. if self.browser.current_window_handle == thisHandle:
  858. break
  859. except Exception as e:
  860. print("关闭标签页发生错误:", e)
  861. print("Error occurred while closing tab: ", e)
  862. if self.history["index"] != thisHistoryLength and self.history[
  863. "handle"] == self.browser.current_window_handle: # 如果执行完一次循环之后历史记录发生了变化,注意当前页面的判断
  864. difference = thisHistoryLength - \
  865. self.history["index"] # 计算历史记录变化差值
  866. self.browser.execute_script(
  867. 'history.go(' + str(difference) + ')') # 回退历史记录
  868. # if node["parameters"]["historyWait"] > 2: # 回退后要等待的时间
  869. time.sleep(node["parameters"]["historyWait"])
  870. # else:
  871. # time.sleep(2)
  872. # 切换历史记录等待:
  873. self.Log("Change history back time or:",
  874. node["parameters"]["historyWait"])
  875. try:
  876. self.browser.execute_script('window.stop()')
  877. except:
  878. pass
  879. if int(node["parameters"]["breakMode"]) > 0: # 如果设置了退出循环的脚本条件
  880. output = self.execute_code(int(
  881. node["parameters"]["breakMode"]) - 1, node["parameters"]["breakCode"], node["parameters"]["breakCodeWaitTime"], iframe=node["parameters"]["iframe"])
  882. code = get_output_code(output)
  883. if code <= 0:
  884. break
  885. except NoSuchElementException:
  886. print("Loop element not found: ", xpath)
  887. print("找不到循环元素: ", xpath)
  888. self.recordLog("pathNotFound: " + node["parameters"]["xpath"])
  889. except Exception as e:
  890. raise
  891. elif int(node["parameters"]["loopType"]) == 2: # 固定元素列表
  892. # 千万不要忘了分割!!
  893. for path in node["parameters"]["pathList"].split("\n"):
  894. try:
  895. path = replace_field_values(path, self.outputParameters)
  896. element = self.browser.find_element(
  897. By.XPATH, path, iframe=node["parameters"]["iframe"])
  898. for i in node["sequence"]: # 挨个执行操作
  899. self.executeNode(i, element, path, 0)
  900. if self.BREAK or self.CONTINUE: # 如果有break操作,下面的操作不执行
  901. self.CONTINUE = False
  902. break
  903. if self.BREAK:
  904. self.BREAK = False
  905. break
  906. try:
  907. changed_handle = self.browser.current_window_handle != thisHandle
  908. except: # 如果网页被意外关闭了的情况下
  909. self.browser.switch_to.window(
  910. self.browser.window_handles[-1])
  911. changed_handle = self.browser.window_handles[-1] != thisHandle
  912. if changed_handle: # 如果执行完一次循环之后标签页的位置发生了变化
  913. try:
  914. while True: # 一直关闭窗口直到当前标签页
  915. self.browser.close() # 关闭使用完的标签页
  916. self.browser.switch_to.window(
  917. self.browser.window_handles[-1])
  918. if self.browser.current_window_handle == thisHandle:
  919. break
  920. except Exception as e:
  921. print("关闭标签页发生错误:", e)
  922. print("Error occurred while closing tab: ", e)
  923. if self.history["index"] != thisHistoryLength and self.history[
  924. "handle"] == self.browser.current_window_handle: # 如果执行完一次循环之后历史记录发生了变化,注意当前页面的判断
  925. difference = thisHistoryLength - \
  926. self.history["index"] # 计算历史记录变化差值
  927. self.browser.execute_script(
  928. 'history.go(' + str(difference) + ')') # 回退历史记录
  929. # if node["parameters"]["historyWait"] > 2: # 回退后要等待的时间
  930. time.sleep(node["parameters"]["historyWait"])
  931. # else:
  932. # time.sleep(2)
  933. self.Log("Change history back time or:",
  934. node["parameters"]["historyWait"])
  935. try:
  936. self.browser.execute_script('window.stop()')
  937. except:
  938. pass
  939. except NoSuchElementException:
  940. print("Loop element not found: ", path)
  941. print("找不到循环元素: ", path)
  942. self.recordLog("pathNotFound: " + path)
  943. continue # 循环中找不到元素就略过操作
  944. except Exception as e:
  945. raise
  946. if int(node["parameters"]["breakMode"]) > 0: # 如果设置了退出循环的脚本条件
  947. output = self.execute_code(int(
  948. node["parameters"]["breakMode"]) - 1, node["parameters"]["breakCode"], node["parameters"]["breakCodeWaitTime"], iframe=node["parameters"]["iframe"])
  949. code = get_output_code(output)
  950. if code <= 0:
  951. break
  952. elif int(node["parameters"]["loopType"]) == 3: # 固定文本列表
  953. textList = node["parameters"]["textList"].split("\n")
  954. for text in textList:
  955. text = replace_field_values(text, self.outputParameters)
  956. self.recordLog("input: " + text)
  957. for i in node["sequence"]: # 挨个执行操作
  958. self.executeNode(i, text, "", 0)
  959. if self.BREAK or self.CONTINUE: # 如果有break操作,下面的操作不执行
  960. self.CONTINUE = False
  961. break
  962. if self.BREAK:
  963. self.BREAK = False
  964. break
  965. if int(node["parameters"]["breakMode"]) > 0: # 如果设置了退出循环的脚本条件
  966. output = self.execute_code(int(
  967. node["parameters"]["breakMode"]) - 1, node["parameters"]["breakCode"], node["parameters"]["breakCodeWaitTime"], iframe=node["parameters"]["iframe"])
  968. code = get_output_code(output)
  969. if code <= 0:
  970. break
  971. elif int(node["parameters"]["loopType"]) == 4: # 固定网址列表
  972. # tempList = node["parameters"]["textList"].split("\r\n")
  973. urlList = list(
  974. filter(isnotnull, node["parameters"]["textList"].split("\n"))) # 去空行
  975. # urlList = []
  976. # for url in tempList:
  977. # if url != "":
  978. # urlList.append(url)
  979. for url in urlList:
  980. url = replace_field_values(url, self.outputParameters)
  981. self.recordLog("input: " + url)
  982. for i in node["sequence"]:
  983. self.executeNode(i, url, "", 0)
  984. if self.BREAK or self.CONTINUE: # 如果有break操作,下面的操作不执行
  985. self.CONTINUE = False
  986. break
  987. if self.BREAK:
  988. self.BREAK = False
  989. break
  990. if int(node["parameters"]["breakMode"]) > 0: # 如果设置了退出循环的脚本条件
  991. output = self.execute_code(int(
  992. node["parameters"]["breakMode"]) - 1, node["parameters"]["breakCode"], node["parameters"]["breakCodeWaitTime"], iframe=node["parameters"]["iframe"])
  993. code = get_output_code(output)
  994. if code <= 0:
  995. break
  996. elif int(node["parameters"]["loopType"]) <= 7: # 命令返回值
  997. while True: # do while循环
  998. if int(node["parameters"]["loopType"]) == 5: # JS
  999. output = self.execute_code(
  1000. 0, node["parameters"]["code"], node["parameters"]["waitTime"], iframe=node["parameters"]["iframe"])
  1001. elif int(node["parameters"]["loopType"]) == 6: # System
  1002. output = self.execute_code(
  1003. 1, node["parameters"]["code"], node["parameters"]["waitTime"], iframe=node["parameters"]["iframe"])
  1004. elif int(node["parameters"]["loopType"]) == 7: # Python
  1005. output = self.execute_code(
  1006. 6, node["parameters"]["code"], node["parameters"]["waitTime"], iframe=node["parameters"]["iframe"])
  1007. code = get_output_code(output)
  1008. if code <= 0:
  1009. break
  1010. for i in node["sequence"]: # 挨个执行操作
  1011. self.executeNode(i, code, node["parameters"]["xpath"], 0)
  1012. if self.BREAK or self.CONTINUE: # 如果有break操作,下面的操作不执行
  1013. self.CONTINUE = False
  1014. break
  1015. if self.BREAK:
  1016. self.BREAK = False
  1017. break
  1018. self.history["index"] = thisHistoryLength
  1019. self.history["handle"] = self.browser.current_window_handle
  1020. self.scrollDown(node["parameters"])
  1021. # 打开网页事件
  1022. def openPage(self, para, loopValue):
  1023. time.sleep(1) # 打开网页后强行等待至少1秒
  1024. if len(self.browser.window_handles) > 1:
  1025. self.browser.switch_to.window(
  1026. self.browser.window_handles[-1]) # 打开网页操作从第1个页面开始
  1027. try:
  1028. self.browser.close()
  1029. except:
  1030. pass
  1031. self.browser.switch_to.window(
  1032. self.browser.window_handles[0]) # 打开网页操作从第1个页面开始
  1033. self.history["handle"] = self.browser.current_window_handle
  1034. if para["useLoop"]:
  1035. url = loopValue
  1036. elif para["url"] != "about:blank":
  1037. url = self.links[self.urlId]
  1038. # clear output parameters
  1039. for key in self.outputParameters:
  1040. self.outputParameters[key] = ""
  1041. else: # 在流程图其他位置设置了打开网页的操作,读取的应该是第一个网址,如打开网页后登录,再打开第二个网页
  1042. url = list(filter(isnotnull, para["links"].split("\n")))[0]
  1043. # 将value中的Field[""]替换为outputParameters中的键值
  1044. url = replace_field_values(url, self.outputParameters)
  1045. try:
  1046. maxWaitTime = int(para["maxWaitTime"])
  1047. except:
  1048. maxWaitTime = 10 # 默认最大等待时间为10秒
  1049. try:
  1050. self.browser.set_page_load_timeout(maxWaitTime) # 加载页面最大超时时间
  1051. self.browser.set_script_timeout(maxWaitTime)
  1052. self.browser.get(url)
  1053. if para["cookies"] != "":
  1054. self.browser.delete_all_cookies() # 清除所有已有cookie
  1055. cookies = para["cookies"].split('\n')
  1056. for cookie in cookies:
  1057. name, value = cookie.split('=', 1)
  1058. cookie_dict = {'name': name, 'value': value}
  1059. # 加载 cookie
  1060. self.browser.add_cookie(cookie_dict)
  1061. self.Log('Loading page: ' + url)
  1062. self.recordLog('Loading page: ' + url)
  1063. except TimeoutException:
  1064. self.Log('Time out after set seconds when loading page: ' + url)
  1065. self.recordLog(
  1066. 'Time out after set seconds when loading page: ' + url)
  1067. try:
  1068. self.browser.execute_script('window.stop()')
  1069. except:
  1070. pass
  1071. except Exception as e:
  1072. print("Failed to load page: " + url)
  1073. self.recordLog('Failed to load page: ' + url)
  1074. try:
  1075. self.history["index"] = self.browser.execute_script(
  1076. "return history.length")
  1077. except TimeoutException:
  1078. try:
  1079. self.browser.execute_script('window.stop()')
  1080. self.history["index"] = self.browser.execute_script(
  1081. "return history.length")
  1082. except:
  1083. self.history["index"] = 0
  1084. self.scrollDown(para) # 控制屏幕向下滚动
  1085. # 键盘输入事件
  1086. def inputInfo(self, para, loopValue):
  1087. time.sleep(0.1) # 输入之前等待0.1秒
  1088. self.Log("Wait 0.1 second before input")
  1089. try:
  1090. xpath = replace_field_values(para["xpath"], self.outputParameters)
  1091. textbox = self.browser.find_element(
  1092. By.XPATH, xpath, iframe=para["iframe"])
  1093. # textbox.send_keys(Keys.CONTROL, 'a')
  1094. # textbox.send_keys(Keys.BACKSPACE)
  1095. self.execute_code(
  1096. 2, para["beforeJS"], para["beforeJSWaitTime"], textbox, iframe=para["iframe"]) # 执行前置JS
  1097. # Send the HOME key
  1098. textbox.send_keys(Keys.HOME)
  1099. # Send the SHIFT + END key combination
  1100. textbox.send_keys(Keys.SHIFT, Keys.END)
  1101. # Send the DELETE key
  1102. textbox.send_keys(Keys.DELETE)
  1103. value = ""
  1104. if para["useLoop"]:
  1105. value = loopValue
  1106. else:
  1107. value = para["value"]
  1108. # 将value中的Field[""]替换为outputParameters中的键值
  1109. pattern = r'Field\["([^"]+)"\]'
  1110. try:
  1111. replaced_text = re.sub(
  1112. pattern, lambda match: self.outputParameters.get(match.group(1), ''), value)
  1113. replaced_text = re.sub(
  1114. '<enter>', '', replaced_text, flags=re.IGNORECASE)
  1115. except:
  1116. replaced_text = value
  1117. index = para["index"]
  1118. if index != 0:
  1119. try:
  1120. replaced_text = replaced_text.split("~")[index - 1]
  1121. except:
  1122. print("取值失败,可能是因为取值索引超出范围,将使用整个文本值")
  1123. print("Failed to get value, maybe because the index is out of range, will use the entire text value")
  1124. textbox.send_keys(replaced_text)
  1125. if value.lower().find("<enter>") >= 0:
  1126. textbox.send_keys(Keys.ENTER)
  1127. self.execute_code(
  1128. 2, para["afterJS"], para["afterJSWaitTime"], textbox, iframe=para["iframe"]) # 执行后置js
  1129. except:
  1130. print("Cannot find input box element:" +
  1131. xpath + ", please try to set the wait time before executing this operation")
  1132. print("找不到输入框元素:" + xpath + ",请尝试在执行此操作前设置等待时间")
  1133. self.recordLog("Cannot find input box element:" +
  1134. para["xpath"] + "Please try to set the wait time before executing this operation")
  1135. # 点击元素事件
  1136. def clickElement(self, para, loopElement=None, clickPath="", index=0):
  1137. try:
  1138. maxWaitTime = int(para["maxWaitTime"])
  1139. except:
  1140. maxWaitTime = 10
  1141. self.browser.set_page_load_timeout(maxWaitTime) # 加载页面最大超时时间
  1142. self.browser.set_script_timeout(maxWaitTime)
  1143. # 点击前对该元素执行一段JavaScript代码
  1144. try:
  1145. # element = self.browser.find_element(
  1146. # By.XPATH, path, iframe=para["iframe"])
  1147. clickPath = replace_field_values(clickPath, self.outputParameters)
  1148. xpath = replace_field_values(para["xpath"], self.outputParameters)
  1149. if para["useLoop"]: # 使用循环的情况下,传入的clickPath就是实际的xpath
  1150. if xpath == "":
  1151. path = clickPath
  1152. else:
  1153. path = "(" + clickPath + ")" + \
  1154. "[" + str(index + 1) + "]" + \
  1155. xpath
  1156. index = 0 # 如果是相对循环内元素的点击,在定位到元素后,index应该重置为0
  1157. # element = loopElement
  1158. else:
  1159. index = 0
  1160. path = xpath # 不然使用元素定义的xpath
  1161. # element = self.browser.find_element(
  1162. # By.XPATH, path, iframe=para["iframe"])
  1163. elements = self.browser.find_elements(
  1164. By.XPATH, path, iframe=para["iframe"])
  1165. element = elements[index]
  1166. if para["beforeJS"] != "":
  1167. self.execute_code(2, para["beforeJS"],
  1168. para["beforeJSWaitTime"], element, iframe=para["iframe"])
  1169. except:
  1170. print("Cannot find element:" +
  1171. path + ", please try to set the wait time before executing this operation")
  1172. print("找不到要点击的元素:" + path + ",请尝试在执行此操作前设置等待时间")
  1173. self.recordLog("Cannot find element:" +
  1174. path + ", please try to set the wait time before executing this operation")
  1175. tempHandleNum = len(self.browser.window_handles) # 记录之前的窗口位置
  1176. try:
  1177. click_way = int(para["clickWay"])
  1178. except:
  1179. click_way = 0
  1180. try:
  1181. if click_way == 0: # 用selenium的点击方法
  1182. actions = ActionChains(self.browser) # 实例化一个action对象
  1183. actions.click(element).perform()
  1184. elif click_way == 1: # 用js的点击方法
  1185. script = 'var result = document.evaluate(`' + path + \
  1186. '`, document, null, XPathResult.ANY_TYPE, null);for(let i=0;i<arguments[0];i++){result.iterateNext();} result.iterateNext().click();'
  1187. self.browser.execute_script(script, str(index)) # 用js的点击方法
  1188. except TimeoutException:
  1189. self.Log('Time out after set seconds when loading clicked page')
  1190. self.recordLog(
  1191. 'Time out after set seconds when loading clicked page')
  1192. try:
  1193. self.browser.execute_script('window.stop()')
  1194. except:
  1195. pass
  1196. except Exception as e:
  1197. self.Log(e)
  1198. self.recordLog(str(e))
  1199. # 点击后对该元素执行一段JavaScript代码
  1200. try:
  1201. if para["afterJS"] != "":
  1202. element = self.browser.find_element(
  1203. By.XPATH, path, iframe=para["iframe"])
  1204. self.execute_code(2, para["afterJS"],
  1205. para["afterJSWaitTime"], element, iframe=para["iframe"])
  1206. except:
  1207. print("Cannot find element:" + path)
  1208. self.recordLog("Cannot find element:" +
  1209. path + ", please try to set the wait time before executing this operation")
  1210. print("找不到要点击的元素:" + path + ",请尝试在执行此操作前设置等待时间")
  1211. waitTime = float(para["wait"]) + 0.01 # 点击之后等待
  1212. try:
  1213. waitType = int(para["waitType"])
  1214. except:
  1215. waitType = 0
  1216. if waitType == 0: # 固定等待时间
  1217. time.sleep(waitTime)
  1218. elif waitType == 1: # 随机等待时间
  1219. time.sleep(random.uniform(waitTime * 0.5, waitTime * 1.5))
  1220. if tempHandleNum != len(self.browser.window_handles): # 如果有新标签页的行为发生
  1221. self.browser.switch_to.window(
  1222. self.browser.window_handles[-1]) # 跳转到新的标签页
  1223. self.history["handle"] = self.browser.current_window_handle
  1224. try:
  1225. self.history["index"] = self.browser.execute_script(
  1226. "return history.length")
  1227. except TimeoutException:
  1228. try:
  1229. self.browser.execute_script('window.stop()')
  1230. except:
  1231. pass
  1232. self.history["index"] = self.browser.execute_script(
  1233. "return history.length")
  1234. else:
  1235. try:
  1236. self.history["index"] = self.browser.execute_script(
  1237. "return history.length")
  1238. except TimeoutException:
  1239. try:
  1240. self.browser.execute_script('window.stop()')
  1241. except:
  1242. pass
  1243. self.history["index"] = self.browser.execute_script(
  1244. "return history.length")
  1245. # 如果打开了新窗口,切换到新窗口
  1246. self.scrollDown(para) # 根据参数配置向下滚动
  1247. # rt.end()
  1248. def get_content(self, p, element):
  1249. content = ""
  1250. if p["contentType"] == 0:
  1251. # 先处理特殊节点类型
  1252. if p["nodeType"] == 2:
  1253. if element.get_attribute("href") != None:
  1254. content = element.get_attribute("href")
  1255. else:
  1256. content = ""
  1257. elif p["nodeType"] == 3:
  1258. if element.get_attribute("value") != None:
  1259. content = element.get_attribute("value")
  1260. else:
  1261. content = ""
  1262. elif p["nodeType"] == 4: # 图片
  1263. if element.get_attribute("src") != None:
  1264. content = element.get_attribute("src")
  1265. else:
  1266. content = ""
  1267. try:
  1268. downloadPic = p["downloadPic"]
  1269. except:
  1270. downloadPic = 0
  1271. if downloadPic == 1:
  1272. download_image(content, "Data/Task_" +
  1273. str(self.id) + "/" + self.saveName + "/")
  1274. else: # 普通节点
  1275. content = element.text
  1276. elif p["contentType"] == 1: # 只采集当期元素下的文本,不包括子元素
  1277. if p["nodeType"] == 2:
  1278. if element.get_attribute("href") != None:
  1279. content = element.get_attribute("href")
  1280. else:
  1281. content = ""
  1282. elif p["nodeType"] == 3:
  1283. if element.get_attribute("value") != None:
  1284. content = element.get_attribute("value")
  1285. else:
  1286. content = ""
  1287. elif p["nodeType"] == 4: # 图片
  1288. if element.get_attribute("src") != None:
  1289. content = element.get_attribute("src")
  1290. else:
  1291. content = ""
  1292. try:
  1293. downloadPic = p["downloadPic"]
  1294. except:
  1295. downloadPic = 0
  1296. if downloadPic == 1:
  1297. download_image(content, "Data/Task_" +
  1298. str(self.id) + "/" + self.saveName + "/")
  1299. else:
  1300. command = 'var arr = [];\
  1301. var content = arguments[0];\
  1302. for(var i = 0, len = content.childNodes.length; i < len; i++) {\
  1303. if(content.childNodes[i].nodeType === 3){ \
  1304. arr.push(content.childNodes[i].nodeValue);\
  1305. }\
  1306. }\
  1307. var str = arr.join(" "); \
  1308. return str;'
  1309. content = self.browser.execute_script(command, element).replace(
  1310. "\n", "").replace("\\s+", " ")
  1311. elif p["contentType"] == 2:
  1312. content = element.get_attribute('innerHTML')
  1313. elif p["contentType"] == 3:
  1314. content = element.get_attribute('outerHTML')
  1315. elif p["contentType"] == 4:
  1316. # 获取元素的背景图片地址
  1317. bg_url = element.value_of_css_property('background-image')
  1318. # 清除背景图片地址中的多余字符
  1319. bg_url = bg_url.replace('url("', '').replace('")', '')
  1320. content = bg_url
  1321. elif p["contentType"] == 5:
  1322. content = self.browser.current_url
  1323. elif p["contentType"] == 6:
  1324. content = self.browser.title
  1325. elif p["contentType"] == 7:
  1326. # 获取整个网页的高度和宽度
  1327. height = self.browser.execute_script(
  1328. "return document.body.scrollHeight")
  1329. width = self.browser.execute_script(
  1330. "return document.body.scrollWidth")
  1331. # 调整浏览器窗口的大小
  1332. self.browser.set_window_size(width, height)
  1333. element.screenshot("Data/Task_" + str(self.id) + "/" + self.saveName +
  1334. "/" + str(time.time()) + ".png")
  1335. elif p["contentType"] == 8:
  1336. try:
  1337. screenshot = element.screenshot_as_png
  1338. screenshot_stream = io.BytesIO(screenshot)
  1339. # 使用Pillow库打开截图,并转换为灰度图像
  1340. image = Image.open(screenshot_stream).convert('L')
  1341. temp_name = "OCR_" + str(time.time()) + ".png"
  1342. location = "Data/Task_" + str(self.id) + "/" + self.saveName + "/" + temp_name
  1343. image.save(location)
  1344. ocr = DdddOcr()
  1345. with open(location, 'rb') as f:
  1346. image_bytes = f.read()
  1347. content = ocr.classification(image_bytes)
  1348. os.remove(location)
  1349. # 使用Tesseract OCR引擎识别图像中的文本
  1350. # content = pytesseract.image_to_string(image, lang='chi_sim+eng')
  1351. except Exception as e:
  1352. # try:
  1353. # print(e)
  1354. # print("识别中文失败,尝试只识别英文")
  1355. # print("Failed to recognize Chinese, try to recognize English only")
  1356. # screenshot = element.screenshot_as_png
  1357. # screenshot_stream = io.BytesIO(screenshot)
  1358. # # 使用Pillow库打开截图,并转换为灰度图像
  1359. # image = Image.open(screenshot_stream).convert('L')
  1360. # # 使用Tesseract OCR引擎识别图像中的文本
  1361. # # content = pytesseract.image_to_string(image, lang='eng')
  1362. # except Exception as e:
  1363. content = "OCR Error"
  1364. print(e)
  1365. # if sys.platform == "win32":
  1366. # print("要使用OCR识别功能,你需要安装Tesseract-OCR并将其添加到环境变量PATH中(添加后需重启EasySpider):https://blog.csdn.net/u010454030/article/details/80515501")
  1367. # print("\nhttps://www.bilibili.com/video/BV1GP411y7u4/")
  1368. # elif sys.platform == "darwin":
  1369. # print(
  1370. # "注意以上错误,要使用OCR识别功能,你需要安装Tesseract-OCR并将其添加到环境变量PATH中(添加后需重启EasySpider):https://zhuanlan.zhihu.com/p/146044810")
  1371. # elif sys.platform == "linux":
  1372. # print(
  1373. # "注意以上错误,要使用OCR识别功能,你需要安装Tesseract-OCR并将其添加到环境变量PATH中(添加后需重启EasySpider):https://zhuanlan.zhihu.com/p/420259031")
  1374. # else:
  1375. # print("注意以上错误,要使用OCR识别功能,你需要安装Tesseract-OCR并将其添加到环境变量PATH中(添加后需重启EasySpider):https://blog.csdn.net/u010454030/article/details/80515501")
  1376. # print("\nhttps://www.bilibili.com/video/BV1GP411y7u4/")
  1377. # print("To use OCR, You need to install Tesseract-OCR and add it to the environment variable PATH (need to restart EasySpider after you put in PATH): https://tesseract-ocr.github.io/tessdoc/Installation.html")
  1378. elif p["contentType"] == 9:
  1379. content = self.execute_code(
  1380. 2, p["JS"], p["JSWaitTime"], element, iframe=p["iframe"])
  1381. elif p["contentType"] == 12: # 系统命令返回值
  1382. content = self.execute_code(1, p["JS"], p["JSWaitTime"])
  1383. elif p["contentType"] == 10: # 下拉框选中的值
  1384. try:
  1385. select_element = Select(element)
  1386. content = select_element.first_selected_option.get_attribute(
  1387. "value")
  1388. except:
  1389. content = ""
  1390. elif p["contentType"] == 11: # 下拉框选中的文本
  1391. try:
  1392. select_element = Select(element)
  1393. content = select_element.first_selected_option.text
  1394. except:
  1395. content = ""
  1396. return content
  1397. def clearOutputParameters(self):
  1398. for key in self.outputParameters:
  1399. self.outputParameters[key] = ""
  1400. # 提取数据事件
  1401. def getData(self, para, loopElement, isInLoop=True, parentPath="", index=0):
  1402. parentPath = replace_field_values(parentPath, self.outputParameters)
  1403. if para["clear"] == 1:
  1404. self.clearOutputParameters()
  1405. try:
  1406. pageHTML = etree.HTML(self.browser.page_source)
  1407. except:
  1408. pageHTML = etree.HTML("")
  1409. if loopElement != "": # 只在数据在循环中提取时才需要获取循环元素
  1410. try:
  1411. loopElementOuterHTML = loopElement.get_attribute('outerHTML')
  1412. except:
  1413. try: # 循环点击每个链接如果没有新标签页打开,loopElement会丢失,此时需要重新获取
  1414. elements = self.browser.find_elements(
  1415. By.XPATH, parentPath, iframe=para["paras"][0]["iframe"])
  1416. loopElement = elements[index]
  1417. loopElementOuterHTML = loopElement.get_attribute(
  1418. 'outerHTML')
  1419. except:
  1420. loopElementOuterHTML = ""
  1421. else:
  1422. loopElementOuterHTML = ""
  1423. loopElementHTML = etree.HTML(loopElementOuterHTML)
  1424. for p in para["paras"]:
  1425. if p["optimizable"]:
  1426. try:
  1427. relativeXPath = replace_field_values(
  1428. p["relativeXPath"], self.outputParameters)
  1429. # 只有当前环境不变变化才可以快速提取数据
  1430. if self.browser.iframe_env != p["iframe"]:
  1431. p["optimizable"] = False
  1432. continue
  1433. # relativeXPath = relativeXPath.lower()
  1434. # relativeXPath = lowercase_tags_in_xpath(relativeXPath)
  1435. # 已经有text()或@href了,不需要再加
  1436. content_type = ""
  1437. if relativeXPath.find("/@href") >= 0 or relativeXPath.find("/text()") >= 0 or relativeXPath.find("::text()") >= 0:
  1438. content_type = ""
  1439. elif p["nodeType"] == 2:
  1440. content_type = "/@href"
  1441. elif p["contentType"] == 1:
  1442. content_type = "/text()"
  1443. elif p["contentType"] == 0:
  1444. content_type = "//text()"
  1445. xpath = relativeXPath + content_type
  1446. if p["relative"]:
  1447. # if relativeXPath == "":
  1448. # content = [loopElementHTML]
  1449. # else:
  1450. # 如果字串里有//即子孙查找,则不动语句
  1451. if relativeXPath.find("//") >= 0:
  1452. if xpath.startswith("/"):
  1453. full_path = "(" + parentPath + ")" + \
  1454. "[" + str(index + 1) + "]"+ \
  1455. relativeXPath + content_type
  1456. else: # 如果是id()这种形式,不需要包parentPath
  1457. full_path = xpath
  1458. try:
  1459. content = pageHTML.xpath(full_path)
  1460. except:
  1461. content = []
  1462. elif not relativeXPath.startswith("/"): # 如果是id()这种形式,不需要包/html/body
  1463. try:
  1464. content = loopElementHTML.xpath(xpath)
  1465. except:
  1466. content = []
  1467. else:
  1468. content = loopElementHTML.xpath(
  1469. "/html/body/" + loopElementHTML[0][0].tag + xpath)
  1470. else:
  1471. if xpath.find("/body") < 0 and xpath.startswith("/"): # 如果是id()或(//div)[1]这种形式,不需要包/html/body
  1472. xpath = "/html/body" + xpath
  1473. content = pageHTML.xpath(xpath)
  1474. if len(content) > 0:
  1475. # html = etree.tostring(content[0], encoding='utf-8').decode('utf-8')
  1476. # 拼接所有文本内容并去掉两边的空白
  1477. content = ' '.join(result.strip()
  1478. for result in content if result.strip())
  1479. if p["nodeType"] == 2:
  1480. base_url = self.browser.current_url
  1481. content = urljoin(base_url, content) # 合并链接相对路径为绝对路径
  1482. else:
  1483. content = p["default"]
  1484. if not self.dataNotFoundKeys[p["name"]]:
  1485. print('Element %s not found with parameter name %s when extracting data, use default, this error will only show once' % (
  1486. relativeXPath, p["name"]))
  1487. print("提取数据操作时,字段名 %s 对应XPath %s 未找到,使用默认值,本字段将不再重复报错" % (
  1488. p["name"], relativeXPath))
  1489. self.dataNotFoundKeys[p["name"]] = True
  1490. self.recordLog(
  1491. 'Element %s not found, use default' % relativeXPath)
  1492. except Exception as e:
  1493. if not self.dataNotFoundKeys[p["name"]]:
  1494. print('Element %s not found with parameter name %s when extracting data, use default, this error will only show once' % (
  1495. relativeXPath, p["name"]))
  1496. print("提取数据操作时,字段名 %s 对应XPath %s 未找到(请查看原因,如是否翻页太快页面元素未加载出来),使用默认值,本字段将不再重复报错" % (
  1497. p["name"], relativeXPath))
  1498. self.dataNotFoundKeys[p["name"]] = True
  1499. self.recordLog(
  1500. 'Element %s not found, use default' % relativeXPath)
  1501. self.outputParameters[p["name"]] = content
  1502. # 对于不能优化的操作,使用selenium执行
  1503. for p in para["paras"]:
  1504. if not p["optimizable"]:
  1505. content = ""
  1506. relativeXPath = replace_field_values(
  1507. p["relativeXPath"], self.outputParameters)
  1508. if not (p["contentType"] == 5 or p["contentType"] == 6): # 如果不是页面标题或URL,去找元素
  1509. try:
  1510. # relativeXPath = relativeXPath.lower()
  1511. # relativeXPath = lowercase_tags_in_xpath(relativeXPath)
  1512. if p["relative"]: # 是否相对xpath
  1513. if relativeXPath == "": # 相对xpath有时候就是元素本身,不需要二次查找
  1514. element = loopElement
  1515. else:
  1516. # 如果字串里有//即子孙查找,则不动语句
  1517. if relativeXPath.find("//") >= 0:
  1518. # full_path = "(" + parentPath + \
  1519. # relativeXPath + ")" + \
  1520. # "[" + str(index + 1) + "]"
  1521. full_path = "(" + parentPath + ")" + \
  1522. "[" + str(index + 1) + "]" + \
  1523. relativeXPath
  1524. element = self.browser.find_element(
  1525. By.XPATH, full_path, iframe=p["iframe"])
  1526. else:
  1527. element = loopElement.find_element(By.XPATH,
  1528. relativeXPath[1:])
  1529. else:
  1530. element = self.browser.find_element(
  1531. By.XPATH, relativeXPath, iframe=p["iframe"])
  1532. except (NoSuchElementException, InvalidSelectorException, StaleElementReferenceException): # 找不到元素的时候,使用默认值
  1533. # print(p)
  1534. try:
  1535. content = p["default"]
  1536. except Exception as e:
  1537. content = ""
  1538. self.outputParameters[p["name"]] = content
  1539. try:
  1540. if not self.dataNotFoundKeys[p["name"]]:
  1541. print('Element %s not found with parameter name %s when extracting data, use default, this error will only show once' % (
  1542. relativeXPath, p["name"]))
  1543. print("提取数据操作时,字段名 %s 对应XPath %s 未找到,使用默认值,本字段将不再重复报错" % (
  1544. p["name"], relativeXPath))
  1545. self.dataNotFoundKeys[p["name"]] = True
  1546. self.recordLog(
  1547. 'Element %s not found, use default' % relativeXPath)
  1548. except:
  1549. pass
  1550. continue
  1551. except TimeoutException: # 超时的时候设置超时值
  1552. self.Log('Time out after set seconds when getting data')
  1553. self.recordLog(
  1554. 'Time out after set seconds when getting data')
  1555. try:
  1556. self.browser.execute_script('window.stop()')
  1557. except:
  1558. pass
  1559. if p["relative"]: # 是否相对xpath
  1560. if relativeXPath == "": # 相对xpath有时候就是元素本身,不需要二次查找
  1561. element = loopElement
  1562. else:
  1563. element = loopElement.find_element(By.XPATH,
  1564. relativeXPath[1:])
  1565. else:
  1566. element = self.browser.find_element(
  1567. By.XPATH, relativeXPath, iframe=p["iframe"])
  1568. # rt.end()
  1569. else:
  1570. element = self.browser.find_element(
  1571. By.XPATH, "//body", iframe=p["iframe"])
  1572. try:
  1573. self.execute_code(
  1574. 2, p["beforeJS"], p["beforeJSWaitTime"], element, iframe=p["iframe"]) # 执行前置js
  1575. content = self.get_content(p, element)
  1576. except StaleElementReferenceException: # 发生找不到元素的异常后,等待几秒重新查找
  1577. self.recordLog(
  1578. 'StaleElementReferenceException: '+relativeXPath)
  1579. time.sleep(3)
  1580. try:
  1581. if p["relative"]: # 是否相对xpath
  1582. if relativeXPath == "": # 相对xpath有时候就是元素本身,不需要二次查找
  1583. element = loopElement
  1584. self.recordLog(
  1585. 'StaleElementReferenceException: loopElement')
  1586. else:
  1587. element = loopElement.find_element(By.XPATH,
  1588. relativeXPath[1:])
  1589. self.recordLog(
  1590. 'StaleElementReferenceException: loopElement+relativeXPath')
  1591. else:
  1592. element = self.browser.find_element(
  1593. By.XPATH, relativeXPath, iframe=p["iframe"])
  1594. self.recordLog(
  1595. 'StaleElementReferenceException: relativeXPath')
  1596. content = self.get_content(p, element)
  1597. except StaleElementReferenceException:
  1598. self.recordLog(
  1599. 'StaleElementReferenceException: '+relativeXPath)
  1600. continue # 再出现类似问题直接跳过
  1601. self.outputParameters[p["name"]] = content
  1602. self.execute_code(
  1603. 2, p["afterJS"], p["afterJSWaitTime"], element, iframe=p["iframe"]) # 执行后置JS
  1604. if para["recordASField"] > 0:
  1605. line = new_line(self.outputParameters, self.maxViewLength, self.outputParametersRecord)
  1606. self.OUTPUT.append(line)
  1607. # rt.end()
  1608. if __name__ == '__main__':
  1609. # from multiprocessing import freeze_support
  1610. # freeze_support() # 防止无限死循环多开
  1611. config = {
  1612. "id": [0],
  1613. "saved_file_name": "",
  1614. "user_data": False,
  1615. "config_folder": "",
  1616. "config_file_name": "config.json",
  1617. "read_type": "remote",
  1618. "headless": False,
  1619. "server_address": "http://localhost:8074",
  1620. "keyboard": True, # 是否监听键盘输入
  1621. "version": "0.3.6",
  1622. }
  1623. c = Config(config)
  1624. print(c)
  1625. options = Options()
  1626. driver_path = "chromedriver.exe"
  1627. import platform
  1628. print(sys.platform, platform.architecture())
  1629. option = webdriver.ChromeOptions()
  1630. if not os.path.exists(os.getcwd()+"/Data"):
  1631. os.mkdir(os.getcwd()+"/Data")
  1632. if sys.platform == "darwin" and platform.architecture()[0] == "64bit":
  1633. options.binary_location = "EasySpider.app/Contents/Resources/app/chrome_mac64.app/Contents/MacOS/Google Chrome"
  1634. # MacOS需要用option而不是options!
  1635. option.binary_location = "EasySpider.app/Contents/Resources/app/chrome_mac64.app/Contents/MacOS/Google Chrome"
  1636. option.add_extension("EasySpider.app/Contents/Resources/app/XPathHelper.crx")
  1637. options.add_extension("EasySpider.app/Contents/Resources/app/XPathHelper.crx")
  1638. driver_path = "EasySpider.app/Contents/Resources/app/chromedriver_mac64"
  1639. # options.binary_location = "chrome_mac64.app/Contents/MacOS/Google Chrome"
  1640. # # MacOS需要用option而不是options!
  1641. # option.binary_location = "chrome_mac64.app/Contents/MacOS/Google Chrome"
  1642. # driver_path = os.getcwd()+ "/chromedriver_mac64"
  1643. print(driver_path)
  1644. if c.config_folder == "":
  1645. c.config_folder = os.path.expanduser("~/Library/Application Support/EasySpider/")
  1646. # print("Config folder for MacOS:", c.config_folder)
  1647. elif os.path.exists(os.getcwd()+"/EasySpider/resources"): # 打包后的路径
  1648. print("Finding chromedriver in EasySpider",
  1649. os.getcwd()+"/EasySpider")
  1650. if sys.platform == "win32" and platform.architecture()[0] == "32bit":
  1651. options.binary_location = os.path.join(
  1652. os.getcwd(), "EasySpider/resources/app/chrome_win32/chrome.exe") # 指定chrome位置
  1653. option.binary_location = os.path.join(
  1654. os.getcwd(), "EasySpider/resources/app/chrome_win32/chrome.exe") # 指定chrome位置
  1655. driver_path = os.path.join(
  1656. os.getcwd(), "EasySpider/resources/app/chrome_win32/chromedriver_win32.exe")
  1657. option.add_extension("EasySpider/resources/app/XPathHelper.crx")
  1658. options.add_extension("EasySpider/resources/app/XPathHelper.crx")
  1659. elif sys.platform == "win32" and platform.architecture()[0] == "64bit":
  1660. options.binary_location = os.path.join(
  1661. os.getcwd(), "EasySpider/resources/app/chrome_win64/chrome.exe")
  1662. option.binary_location = os.path.join(
  1663. os.getcwd(), "EasySpider/resources/app/chrome_win64/chrome.exe")
  1664. driver_path = os.path.join(
  1665. os.getcwd(), "EasySpider/resources/app/chrome_win64/chromedriver_win64.exe")
  1666. option.add_extension("EasySpider/resources/app/XPathHelper.crx")
  1667. options.add_extension("EasySpider/resources/app/XPathHelper.crx")
  1668. elif sys.platform == "linux" and platform.architecture()[0] == "64bit":
  1669. options.binary_location = "EasySpider/resources/app/chrome_linux64/chrome"
  1670. option.binary_location = "EasySpider/resources/app/chrome_linux64/chrome"
  1671. driver_path = "EasySpider/resources/app/chrome_linux64/chromedriver_linux64"
  1672. option.add_extension("EasySpider/resources/app/XPathHelper.crx")
  1673. options.add_extension("EasySpider/resources/app/XPathHelper.crx")
  1674. else:
  1675. print("Unsupported platform")
  1676. sys.exit()
  1677. print("Chrome location:", options.binary_location)
  1678. print("Chromedriver location:", driver_path)
  1679. # elif os.getcwd().find("ExecuteStage") >= 0: # 如果直接执行
  1680. # print("Finding chromedriver in ./Chrome",
  1681. # os.getcwd()+"/Chrome")
  1682. # options.binary_location = "./Chrome/chrome.exe" # 指定chrome位置
  1683. # # option.binary_location = "C:\\Users\\q9823\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe"
  1684. # driver_path = "./Chrome/chromedriver.exe"
  1685. elif os.path.exists(os.getcwd()+"/../ElectronJS"):
  1686. # 软件dev用
  1687. print("Finding chromedriver in EasySpider",
  1688. os.getcwd()+"/ElectronJS")
  1689. option.binary_location = "../ElectronJS/chrome_win64/chrome.exe" # 指定chrome位置
  1690. options.binary_location = "../ElectronJS/chrome_win64/chrome.exe" # 指定chrome位置
  1691. driver_path = "../ElectronJS/chrome_win64/chromedriver_win64.exe"
  1692. option.add_extension("../ElectronJS/XPathHelper.crx")
  1693. else:
  1694. options.binary_location = "./chrome.exe" # 指定chrome位置
  1695. driver_path = "./chromedriver.exe"
  1696. option.add_extension("XPathHelper.crx")
  1697. option.add_experimental_option(
  1698. 'excludeSwitches', ['enable-automation']) # 以开发者模式
  1699. # user_data_dir = r'' # 注意没有Default!
  1700. # options.add_argument('--user-data-dir='+p)
  1701. # 总结:
  1702. # 0. 带Cookie需要用userdatadir
  1703. # 1. chrome_options才是配置用户文件和chrome文件地址的正确选项
  1704. # 2. User Profile文件夹的路径是:C:\Users\用户名\AppData\Local\Google\Chrome\User Data不要加Default
  1705. # 3. 就算User Profile相同,chrome版本不同所存储的cookie信息也不同,也不能爬
  1706. # 4. TMALL如果一直弹出验证码,而且无法通过验证,那么需要在其他浏览器上用
  1707. try:
  1708. with open(c.config_folder + c.config_file_name, "r", encoding='utf-8') as f:
  1709. config = json.load(f)
  1710. print("Config file path: " + c.config_folder + c.config_file_name)
  1711. absolute_user_data_folder = config["absolute_user_data_folder"]
  1712. print("\nAbsolute_user_data_folder:",
  1713. absolute_user_data_folder, "\n")
  1714. except:
  1715. pass
  1716. if c.user_data:
  1717. option.add_argument(
  1718. f'--user-data-dir={absolute_user_data_folder}') # TMALL 反扒
  1719. option.add_argument("--profile-directory=Default")
  1720. options.add_argument(
  1721. f'--user-data-dir={absolute_user_data_folder}') # TMALL 反扒
  1722. options.add_argument("--profile-directory=Default")
  1723. if c.headless:
  1724. print("Headless mode")
  1725. print("无头模式")
  1726. option.add_argument("--headless")
  1727. options.add_argument("--headless")
  1728. # options.add_argument(
  1729. # '--user-data-dir=C:\\Users\\q9823\\AppData\\Local\\Google\\Chrome\\User Data') # TMALL 反扒
  1730. option.add_argument(
  1731. "--disable-blink-features=AutomationControlled") # TMALL 反扒
  1732. options.add_argument(
  1733. "--disable-blink-features=AutomationControlled") # TMALL 反扒
  1734. threads = []
  1735. for i in c.id:
  1736. # print(options)
  1737. print("id: ", i)
  1738. if c.read_type == "remote":
  1739. print("remote")
  1740. content = requests.get(
  1741. c.server_address + "/queryExecutionInstance?id=" + str(i))
  1742. service = json.loads(content.text) # 加载服务信息
  1743. else:
  1744. print("local")
  1745. with open("execution_instances/" + str(i) + ".json", 'r', encoding='utf-8') as f:
  1746. content = f.read()
  1747. service = json.loads(content) # 加载服务信息
  1748. print("Task Name:", service["name"])
  1749. print("任务名称:", service["name"])
  1750. try:
  1751. cloudflare = service["cloudflare"]
  1752. except:
  1753. cloudflare = 0
  1754. if cloudflare == 0:
  1755. options.add_argument('log-level=3') # 隐藏日志
  1756. option.add_argument('log-level=3') # 隐藏日志
  1757. options.add_experimental_option("prefs", {
  1758. # 设置文件下载路径
  1759. "download.default_directory": "Data/Task_" + str(i),
  1760. "download.prompt_for_download": False, # 禁止下载提示框
  1761. "plugins.plugins_list": [{"enabled": False, "name": "Chrome PDF Viewer"}],
  1762. "download.directory_upgrade": True,
  1763. "download.extensions_to_open": "applications/pdf",
  1764. "plugins.always_open_pdf_externally": True # 总是在外部程序中打开PDF
  1765. })
  1766. option.add_experimental_option("prefs", {
  1767. # 设置文件下载路径
  1768. "download.default_directory": "Data/Task_" + str(i),
  1769. "download.prompt_for_download": False, # 禁止下载提示框
  1770. "plugins.plugins_list": [{"enabled": False, "name": "Chrome PDF Viewer"}],
  1771. "download.directory_upgrade": True,
  1772. "download.extensions_to_open": "applications/pdf",
  1773. "plugins.always_open_pdf_externally": True # 总是在外部程序中打开PDF
  1774. })
  1775. try:
  1776. if service["environment"] == 1:
  1777. option.add_experimental_option(
  1778. 'mobileEmulation', {'deviceName': 'iPhone X'}) # 模拟iPhone X浏览
  1779. options.add_experimental_option(
  1780. 'mobileEmulation', {'deviceName': 'iPhone X'}) # 模拟iPhone X浏览
  1781. except:
  1782. pass
  1783. browser_t = MyChrome(
  1784. options=options, chrome_options=option, executable_path=driver_path)
  1785. elif cloudflare == 1:
  1786. if sys.platform == "win32":
  1787. options.binary_location = "C:\\Program Files\\Google\\Chrome Beta\\Application\\chrome.exe" # 需要用自己的浏览器
  1788. # options.binary_location = "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe" # 需要用自己的浏览器
  1789. browser_t = MyUCChrome(
  1790. options=options, driver_executable_path=driver_path)
  1791. else:
  1792. print("Cloudflare模式只支持Windows x64平台。")
  1793. print("Cloudflare Mode only support on Windows x64 platform.")
  1794. sys.exit()
  1795. event = Event()
  1796. event.set()
  1797. thread = BrowserThread(browser_t, i, service,
  1798. c.version, event, c.saved_file_name, config=config)
  1799. print("Thread with task id: ", i, " is created")
  1800. threads.append(thread)
  1801. thread.start()
  1802. # Set the pause operation
  1803. # if sys.platform != "linux":
  1804. # time.sleep(3)
  1805. # print("\n\n----------------------------------")
  1806. # print("正在运行任务,长按键盘p键可暂停任务的执行以便手工操作浏览器如输入验证码;如果想恢复任务的执行,请再次长按p键。")
  1807. # print("Running task, long press 'p' to pause the task for manual operation of the browser such as entering the verification code; If you want to resume the execution of the task, please long press 'p' again.")
  1808. # print("----------------------------------\n\n")
  1809. # Thread(target=check_pause, args=("p", event)).start()
  1810. # else:
  1811. time.sleep(3)
  1812. press_time = {"duration": 0, "is_pressed": False}
  1813. print("\n\n----------------------------------")
  1814. print("正在运行任务,长按键盘p键可暂停任务的执行以便手工操作浏览器如输入验证码;如果想恢复任务的执行,请再次长按p键。")
  1815. print("Running task, long press 'p' to pause the task for manual operation of the browser such as entering the verification code; If you want to resume the execution of the task, please long press 'p' again.")
  1816. print("----------------------------------\n\n")
  1817. # if cloudflare:
  1818. # print("过Cloudflare验证模式有时候会不稳定,如果无法通过验证则需要隔几分钟重试一次,或者可以更换新的用户信息文件夹再执行任务。")
  1819. # print("Passing the Cloudflare verification mode is sometimes unstable. If the verification fails, you need to try again every few minutes, or you can change to a new user information folder and then execute the task.")
  1820. # 使用监听器监听键盘输入
  1821. try:
  1822. if c.keyboard:
  1823. with Listener(on_press=on_press_creator(press_time, event), on_release=on_release_creator(event, press_time)) as listener:
  1824. listener.join()
  1825. except:
  1826. pass
  1827. # print("您的操作系统不支持暂停功能。")
  1828. # print("Your operating system does not support the pause function.")
  1829. # print("线程长度:", len(threads) )
  1830. for thread in threads:
  1831. print()
  1832. thread.join()
  1833. for thread in threads:
  1834. thread.browser.quit()
  1835. # print("Thread with task id: ", thread.id, " is closed")
  1836. print("程序已运行完成,请手动关闭此窗口。")
  1837. print("The program has finished running, please manually close this window.")