easyspider_executestage.py 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104
  1. # -*- coding: utf-8 -*-
  2. import atexit
  3. import io # 遇到错误退出时应执行的代码
  4. import json
  5. from lib2to3.pgen2 import driver
  6. import re
  7. import subprocess
  8. import sys
  9. from urllib import parse
  10. import base64
  11. import hashlib
  12. import time
  13. import requests
  14. from selenium.webdriver.chrome.options import Options
  15. from selenium.webdriver.common.keys import Keys
  16. from selenium.webdriver.common.action_chains import ActionChains
  17. from selenium import webdriver
  18. from selenium.webdriver.support.ui import WebDriverWait
  19. from selenium.webdriver.support import expected_conditions as EC
  20. from selenium.webdriver.common.by import By
  21. from selenium.common.exceptions import NoSuchElementException
  22. from selenium.common.exceptions import TimeoutException
  23. from selenium.common.exceptions import StaleElementReferenceException, InvalidSelectorException
  24. from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
  25. from selenium.webdriver.support.ui import Select
  26. from selenium.webdriver import ActionChains
  27. import random
  28. # import numpy
  29. import csv
  30. import os
  31. from selenium.webdriver.common.by import By
  32. from commandline_config import Config
  33. import pytesseract
  34. from PIL import Image
  35. import uuid
  36. from threading import Thread
  37. desired_capabilities = DesiredCapabilities.CHROME
  38. desired_capabilities["pageLoadStrategy"] = "none"
  39. def download_image(url, save_directory):
  40. # 定义浏览器头信息
  41. headers = {
  42. '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'
  43. }
  44. # 发送 GET 请求获取图片数据
  45. response = requests.get(url, headers=headers)
  46. # 检查响应状态码是否为成功状态
  47. if response.status_code == requests.codes.ok:
  48. # 提取文件名
  49. file_name = url.split('/')[-1]
  50. # 生成唯一的新文件名
  51. new_file_name = str(uuid.uuid4()) + '_' + file_name
  52. # 构建保存路径
  53. save_path = os.path.join(save_directory, new_file_name)
  54. # 保存图片到本地
  55. with open(save_path, 'wb') as file:
  56. file.write(response.content)
  57. print("图片已成功下载到:", save_path)
  58. print("The image has been successfully downloaded to:", save_path)
  59. else:
  60. print("下载图片失败,请检查此图片链接是否有效:", url)
  61. print("Failed to download image, please check if this image link is valid:", url)
  62. def get_output_code(output):
  63. try:
  64. if output.find("rue") != -1: # 如果返回值中包含true
  65. code = 1
  66. else:
  67. code = int(output)
  68. except:
  69. code = 0
  70. return code
  71. # 判断字段是否为空
  72. def isnull(s):
  73. return len(s) != 0
  74. class Time:
  75. def __init__(self, type1=""):
  76. self.t = int(round(time.time() * 1000))
  77. self.type = type1
  78. def end(self):
  79. at = int(round(time.time() * 1000))
  80. print("Time used for", self.type, ":", at - self.t, "ms")
  81. class BrowserThread(Thread):
  82. def __init__(self, browser_t, id, saved_file_name, read_type, server_address, version):
  83. Thread.__init__(self)
  84. self.browser = browser_t
  85. self.id = id
  86. self.saved_file_name = saved_file_name
  87. self.saveName = None
  88. self.log = ""
  89. self.OUTPUT = ""
  90. self.SAVED = False
  91. stealth_path = driver_path[:driver_path.find("chromedriver")] + "stealth.min.js"
  92. with open(stealth_path, 'r') as f:
  93. js = f.read()
  94. print("Loading stealth.min.js")
  95. self.browser.execute_cdp_cmd('Page.addScriptToEvaluateOnNewDocument', {'source': js}) # TMALL 反扒
  96. WebDriverWait(self.browser, 10)
  97. self.browser.get('about:blank')
  98. print("id: ", id)
  99. if saved_file_name != "":
  100. self.saveName = "task_" + str(id) + "_" + saved_file_name # 保存文件的名字
  101. else:
  102. self.saveName = "task_" + str(id) + "_" + \
  103. str(random.randint(0, 999999999)) # 保存文件的名字
  104. print("Save Name for task id", id, "is:", self.saveName)
  105. print("任务id", id, "的保存文件名为:", self.saveName)
  106. os.mkdir("Data/" + self.saveName) # 创建保存文件夹用来保存截图
  107. if read_type == "remote":
  108. print("remote")
  109. content = requests.get(server_address + "/queryExecutionInstance?id=" + str(id))
  110. service = json.loads(content.text) # 加载服务信息
  111. else:
  112. print("local")
  113. with open("execution_instances/" + str(id) + ".json", 'r', encoding='utf-8') as f:
  114. content = f.read()
  115. service = json.loads(content) # 加载服务信息
  116. print("Task Name:", service["name"])
  117. print("任务名称:", service["name"])
  118. self.procedure = service["graph"] # 程序执行流程
  119. try:
  120. if service["version"] != version:
  121. print("版本不一致,请使用" + service["version"] + "版本的EasySpider运行该任务")
  122. print("Version not match, please use EasySpider " + service["version"] + " to run this task")
  123. self.browser.quit()
  124. sys.exit()
  125. except:
  126. print("版本不一致,请使用v0.2.0版本的EasySpider运行该任务")
  127. print("Version not match, please use EasySpider v0.2.0 to run this task")
  128. self.browser.quit()
  129. sys.exit()
  130. self.links = list(filter(isnull, service["links"].split("\n"))) # 要执行的link的列表
  131. self.OUTPUT = [] # 采集的数据
  132. self.OUTPUT.append([]) # 添加表头
  133. self.containJudge = service["containJudge"] # 是否含有判断语句
  134. self.bodyText = "" # 记录bodyText
  135. tOut = service["outputParameters"] # 生成输出参数对象
  136. self.outputParameters = {}
  137. self.dataNotFoundKeys = {} # 记录没有找到数据的key
  138. self.log = "" # 记下现在总共开了多少个标签页
  139. self.history = {"index": 0, "handle": None} # 记录页面现在所以在的历史记录的位置
  140. self.SAVED = False # 记录是否已经存储了
  141. for para in tOut:
  142. self.outputParameters[para["name"]] = ""
  143. self.dataNotFoundKeys[para["name"]] = False
  144. self.OUTPUT[0].append(para["name"])
  145. self.urlId = 0 # 全局记录变量
  146. def run(self):
  147. # 挨个执行程序
  148. for i in range(len(self.links)):
  149. self.executeNode(0)
  150. self.urlId = self.urlId + 1
  151. files = os.listdir("Data/" + self.saveName)
  152. # 如果目录为空,则删除该目录
  153. if not files:
  154. os.rmdir("Data/" + self.saveName)
  155. print("Done!")
  156. print("执行完成!")
  157. self.recordLog("Done!")
  158. self.saveData(exit=True)
  159. def recordLog(self, str=""):
  160. self.log = self.log + str + "\n"
  161. # 控制台打印log函数
  162. def Log(self, text, text2=""):
  163. switch = False
  164. if switch:
  165. print(text, text2)
  166. # @atexit.register
  167. # def clean(self):
  168. # self.saveData(exit=True)
  169. # self.browser.quit()
  170. # sys.exit(0)
  171. def saveData(self, exit=False):
  172. if exit == True or len(self.OUTPUT) >= 100: # 每100条保存一次
  173. with open("Data/"+ self.saveName + '_log.txt', 'a', encoding='utf-8-sig') as file_obj:
  174. file_obj.write(self.log)
  175. file_obj.close()
  176. with open("Data/"+ self.saveName + '.csv', 'a', encoding='utf-8-sig', newline="") as f:
  177. f_csv = csv.writer(f)
  178. for line in self.OUTPUT:
  179. f_csv.writerow(line)
  180. f.close()
  181. self.OUTPUT = []
  182. self.log = ""
  183. def scrollDown(self, para, rt=""):
  184. time.sleep(para["scrollWaitTime"]) # 下拉前等待
  185. scrollType = int(para["scrollType"])
  186. try:
  187. if scrollType != 0 and para["scrollCount"] > 0: # 控制屏幕向下滚动
  188. for i in range(para["scrollCount"]):
  189. self.Log("Wait for set second after screen scrolling")
  190. body = self.browser.find_element(By.CSS_SELECTOR, "body")
  191. if scrollType == 1:
  192. body.send_keys(Keys.PAGE_DOWN)
  193. elif scrollType == 2:
  194. body.send_keys(Keys.END)
  195. time.sleep(para["scrollWaitTime"]) # 下拉完等待
  196. except:
  197. self.Log('time out after set seconds when scrolling. ')
  198. self.recordLog('time out after set seconds when scrolling')
  199. self.browser.execute_script('window.stop()')
  200. if scrollType != 0 and para["scrollCount"] > 0: # 控制屏幕向下滚动
  201. for i in range(para["scrollCount"]):
  202. self.Log("Wait for set second after screen scrolling")
  203. body = self.browser.find_element(By.CSS_SELECTOR, "body")
  204. if scrollType == 1:
  205. body.send_keys(Keys.PGDN)
  206. elif scrollType == 2:
  207. body.send_keys(Keys.END)
  208. time.sleep(para["scrollWaitTime"]) # 下拉完等待
  209. if rt != "":
  210. rt.end()
  211. def execute_code(self, codeMode, code, max_wait_time, element=None):
  212. output = ""
  213. if code == "":
  214. return ""
  215. if max_wait_time == 0:
  216. max_wait_time = 999999
  217. # print(codeMode, code)
  218. if int(codeMode) == 0:
  219. self.recordLog("Execute JavaScript:" + code)
  220. self.recordLog("执行JavaScript:" + code)
  221. self.browser.set_script_timeout(max_wait_time)
  222. try:
  223. output = self.browser.execute_script(code)
  224. except:
  225. output = ""
  226. self.recordLog("JavaScript execution failed")
  227. elif int(codeMode) == 2:
  228. self.recordLog("Execute JavaScript for element:" + code)
  229. self.recordLog("对元素执行JavaScript:" + code)
  230. self.browser.set_script_timeout(max_wait_time)
  231. try:
  232. output = self.browser.execute_script(code, element)
  233. except:
  234. output = ""
  235. self.recordLog("JavaScript execution failed")
  236. elif int(codeMode) == 1:
  237. self.recordLog("Execute System Call:" + code)
  238. self.recordLog("执行系统命令:" + code)
  239. # 执行系统命令,超时时间为5秒
  240. try:
  241. output = subprocess.run(code, capture_output=True, text=True, timeout=max_wait_time, encoding="utf-8")
  242. # 输出命令返回值
  243. output = output.stdout
  244. print(output)
  245. except subprocess.TimeoutExpired:
  246. # 命令执行时间超过5秒,抛出异常
  247. self.recordLog("Command timed out")
  248. self.recordLog("命令执行超时")
  249. except:
  250. self.recordLog("Command execution failed")
  251. self.recordLog("命令执行失败")
  252. return str(output)
  253. def customOperation(self, node, loopValue, loopPath, index):
  254. paras = node["parameters"]
  255. codeMode = int(paras["codeMode"])
  256. code = paras["code"]
  257. max_wait_time = int(paras["waitTime"])
  258. if codeMode == 2: # 使用循环的情况下,传入的clickPath就是实际的xpath
  259. try:
  260. elements = self.browser.find_elements(By.XPATH, loopPath)
  261. element = elements[index]
  262. output = self.execute_code(codeMode, code, max_wait_time, element)
  263. except:
  264. output = ""
  265. print("JavaScript execution failed")
  266. else:
  267. output = self.execute_code(codeMode, code, max_wait_time)
  268. recordASField = int(paras["recordASField"])
  269. if recordASField:
  270. self.outputParameters[node["title"]] = output
  271. line = []
  272. for value in self.outputParameters.values():
  273. line.append(value)
  274. print(value[:15], " ", end="")
  275. print("")
  276. self.OUTPUT.append(line)
  277. def switchSelect(self, para, loopValue):
  278. optionMode = int(para["optionMode"])
  279. optionValue = para["optionValue"]
  280. try:
  281. dropdown = Select(self.browser.find_element(By.XPATH, para["xpath"]))
  282. try:
  283. if optionMode == 0:
  284. # 获取当前选中的选项索引
  285. current_index = dropdown.options.index(dropdown.first_selected_option)
  286. # 计算下一个选项的索引
  287. next_index = (current_index + 1) % len(dropdown.options)
  288. # 选择下一个选项
  289. dropdown.select_by_index(next_index)
  290. elif optionMode == 1:
  291. dropdown.select_by_index(int(optionValue))
  292. elif optionMode == 2:
  293. dropdown.select_by_value(optionValue)
  294. elif optionMode == 3:
  295. dropdown.select_by_visible_text(optionValue)
  296. except:
  297. print("切换下拉框选项失败:", para["xpath"], para["optionMode"], para["optionValue"])
  298. print("Failed to change drop-down box option:", para["xpath"], para["optionMode"], para["optionValue"])
  299. except:
  300. print("找不到下拉框元素:", para["xpath"])
  301. print("Cannot find drop-down box element:", para["xpath"])
  302. def moveToElement(self, para, loopElement=None, loopPath="", index=0):
  303. time.sleep(0.1) # 移动之前等待0.1秒
  304. if para["useLoop"]: # 使用循环的情况下,传入的clickPath就是实际的xpath
  305. path = loopPath
  306. else:
  307. index = 0
  308. path = para["xpath"] # 不然使用元素定义的xpath
  309. try:
  310. elements = self.browser.find_elements(By.XPATH, path)
  311. element = elements[index]
  312. try:
  313. ActionChains(self.browser).move_to_element(element).perform()
  314. except:
  315. print("移动鼠标到元素失败:", para["xpath"])
  316. print("Failed to move mouse to element:", para["xpath"])
  317. except:
  318. print("找不到元素:", para["xpath"])
  319. print("Cannot find element:", para["xpath"])
  320. # 执行节点关键函数部分
  321. def executeNode(self, nodeId, loopValue="", loopPath="", index=0):
  322. node = self.procedure[nodeId]
  323. WebDriverWait(self.browser, 10).until
  324. # 等待元素出现才进行操作,10秒内未出现则报错
  325. (EC.visibility_of_element_located((By.XPATH, node["parameters"]["xpath"])))
  326. # 根据不同选项执行不同操作
  327. if node["option"] == 0 or node["option"] == 10: # root操作,条件分支操作
  328. for i in node["sequence"]: # 从根节点开始向下读取
  329. self.executeNode(i, loopValue, loopPath, index)
  330. elif node["option"] == 1: # 打开网页操作
  331. self.recordLog("openPage")
  332. self.openPage(node["parameters"], loopValue)
  333. elif node["option"] == 2: # 点击元素
  334. self.recordLog("Click")
  335. self.clickElement(node["parameters"], loopValue, loopPath, index)
  336. elif node["option"] == 3: # 提取数据
  337. self.recordLog("getData")
  338. self.getData(node["parameters"], loopValue, node["isInLoop"],
  339. parentPath=loopPath, index=index)
  340. self.saveData()
  341. elif node["option"] == 4: # 输入文字
  342. self.inputInfo(node["parameters"], loopValue)
  343. elif node["option"] == 5: # 自定义操作
  344. self.customOperation(node, loopValue, loopPath, index)
  345. self.saveData()
  346. elif node["option"] == 6: # 切换下拉框
  347. self.switchSelect(node["parameters"], loopValue)
  348. elif node["option"] == 7: # 鼠标移动到元素上
  349. self.moveToElement(node["parameters"], loopValue, loopPath, index)
  350. elif node["option"] == 8: # 循环
  351. self.recordLog("loop")
  352. self.loopExecute(node, loopValue, loopPath, index) # 执行循环
  353. elif node["option"] == 9: # 条件分支
  354. self.recordLog("judge")
  355. self.judgeExecute(node, loopValue, loopPath, index)
  356. # 执行完之后进行等待
  357. if node["option"] != 0:
  358. waitTime = 0.01 # 默认等待0.01秒
  359. if node["parameters"]["wait"] > 1:
  360. waitTime = node["parameters"]["wait"]
  361. time.sleep(waitTime)
  362. self.Log("Wait seconds after node executing: ", waitTime)
  363. # 对判断条件的处理
  364. def judgeExecute(self, node, loopElement, clickPath="", index=0):
  365. executeBranchId = 0 # 要执行的BranchId
  366. for i in node["sequence"]:
  367. cnode = self.procedure[i] # 获得条件分支
  368. tType = int(cnode["parameters"]["class"]) # 获得判断条件类型
  369. if tType == 0: # 什么条件都没有
  370. executeBranchId = i
  371. break
  372. elif tType == 1: # 当前页面包含文本
  373. try:
  374. if self.bodyText.find(cnode["parameters"]["value"]) >= 0:
  375. executeBranchId = i
  376. break
  377. except: # 找不到元素下一个条件
  378. continue
  379. elif tType == 2: # 当前页面包含元素
  380. try:
  381. if self.browser.find_element(By.XPATH, cnode["parameters"]["value"]):
  382. executeBranchId = i
  383. break
  384. except: # 找不到元素或者xpath写错了,下一个条件
  385. continue
  386. elif tType == 3: # 当前循环元素包括文本
  387. try:
  388. if loopElement.text.find(cnode["parameters"]["value"]) >= 0:
  389. executeBranchId = i
  390. break
  391. except: # 找不到元素或者xpath写错了,下一个条件
  392. continue
  393. elif tType == 4: # 当前循环元素包括元素
  394. try:
  395. if loopElement.find_element(By.XPATH, cnode["parameters"]["value"][1:]):
  396. executeBranchId = i
  397. break
  398. except: # 找不到元素或者xpath写错了,下一个条件
  399. continue
  400. elif tType <= 7: # JS命令返回值
  401. if tType == 5: # JS命令返回值等于
  402. output = self.execute_code(0, cnode["parameters"]["code"], cnode["parameters"]["waitTime"])
  403. elif tType == 6: # System
  404. output = self.execute_code(1, cnode["parameters"]["code"], cnode["parameters"]["waitTime"])
  405. elif tType == 7: # 针对当前循环项的JS命令返回值
  406. output = self.execute_code(2, cnode["parameters"]["code"], cnode["parameters"]["waitTime"], loopElement)
  407. try:
  408. if output.find("rue") != -1: # 如果返回值中包含true
  409. code = 1
  410. else:
  411. code = int(output)
  412. except:
  413. code = 0
  414. if code > 0:
  415. executeBranchId = i
  416. break
  417. # rt.end()
  418. if executeBranchId != 0:
  419. self.executeNode(executeBranchId, loopElement, clickPath, index)
  420. # 对循环的处理
  421. def loopExecute(self, node, loopValue, clickPath="", index=0):
  422. time.sleep(0.1) # 第一次执行循环的时候强制等待1秒
  423. # self.Log("循环执行前等待0.1秒")
  424. self.Log("Wait 0.1 second before loop")
  425. thisHandle = self.browser.current_window_handle # 记录本次循环内的标签页的ID
  426. thisHistoryLength = self.browser.execute_script(
  427. 'return history.length') # 记录本次循环内的history的length
  428. self.history["index"] = thisHistoryLength
  429. self.history["handle"] = thisHandle
  430. if int(node["parameters"]["loopType"]) == 0: # 单个元素循环
  431. # 无跳转标签页操作
  432. count = 0 # 执行次数
  433. while True: # do while循环
  434. try:
  435. finished = False
  436. element = self.browser.find_element(
  437. By.XPATH, node["parameters"]["xpath"])
  438. for i in node["sequence"]: # 挨个执行操作
  439. self.executeNode(i, element, node["parameters"]["xpath"], 0)
  440. finished = True
  441. self.Log("click: ", node["parameters"]["xpath"])
  442. self.recordLog("click:" + node["parameters"]["xpath"])
  443. except NoSuchElementException:
  444. # except:
  445. print("Single loop element not found: ", node["parameters"]["xpath"])
  446. print("找不到要循环的单个元素: ", node["parameters"]["xpath"])
  447. self.recordLog("Single loop element not found: " + node["parameters"]["xpath"])
  448. for i in node["sequence"]: # 不带点击元素的把剩余的如提取数据的操作执行一遍
  449. if node["option"] != 2:
  450. self.executeNode(i, None, node["parameters"]["xpath"], 0)
  451. finished = True
  452. break # 如果找不到元素,退出循环
  453. finally:
  454. if not finished:
  455. print("\n\n-------Retrying-------\n\n")
  456. self.Log("-------Retrying-------: ",
  457. node["parameters"]["xpath"])
  458. self.recordLog("clickNotFound:" + node["parameters"]["xpath"])
  459. for i in node["sequence"]: # 不带点击元素的把剩余的如提取数据的操作执行一遍
  460. if node["option"] != 2:
  461. self.executeNode(i, None, node["parameters"]["xpath"], 0)
  462. break # 如果找不到元素,退出循环
  463. count = count + 1
  464. self.Log("Page: ", count)
  465. self.recordLog("Page:" + str(count))
  466. # print(node["parameters"]["exitCount"], "-------")
  467. if node["parameters"]["exitCount"] == count: # 如果达到设置的退出循环条件的话
  468. break
  469. if int(node["parameters"]["breakMode"]) > 0: # 如果设置了退出循环的脚本条件
  470. output = self.execute_code(int(node["parameters"]["breakMode"]) -1, node["parameters"]["breakCode"], node["parameters"]["breakCodeWaitTime"])
  471. code = get_output_code(output)
  472. if code <= 0:
  473. break
  474. elif int(node["parameters"]["loopType"]) == 1: # 不固定元素列表
  475. try:
  476. elements = self.browser.find_elements(By.XPATH,
  477. node["parameters"]["xpath"])
  478. if len(elements) == 0:
  479. print("Loop element not found: ", node["parameters"]["xpath"])
  480. print("找不到循环元素: ", node["parameters"]["xpath"])
  481. self.recordLog("pathNotFound: " + node["parameters"]["xpath"])
  482. for index in range(len(elements)):
  483. for i in node["sequence"]: # 挨个顺序执行循环里所有的操作
  484. self.executeNode(i, elements[index],
  485. node["parameters"]["xpath"], index)
  486. if self.browser.current_window_handle != thisHandle: # 如果执行完一次循环之后标签页的位置发生了变化
  487. while True: # 一直关闭窗口直到当前标签页
  488. self.browser.close() # 关闭使用完的标签页
  489. self.browser.switch_to.window(self.browser.window_handles[-1])
  490. if self.browser.current_window_handle == thisHandle:
  491. break
  492. if self.history["index"] != thisHistoryLength and self.history[
  493. "handle"] == self.browser.current_window_handle: # 如果执行完一次循环之后历史记录发生了变化,注意当前页面的判断
  494. difference = thisHistoryLength - \
  495. self.history["index"] # 计算历史记录变化差值
  496. self.browser.execute_script(
  497. 'history.go(' + str(difference) + ')') # 回退历史记录
  498. if node["parameters"]["historyWait"] > 2: # 回退后要等待的时间
  499. time.sleep(node["parameters"]["historyWait"])
  500. else:
  501. time.sleep(2)
  502. # 切换历史记录等待2秒或者:
  503. self.Log("Change history back time or:",
  504. node["parameters"]["historyWait"])
  505. self.browser.execute_script('window.stop()')
  506. if int(node["parameters"]["breakMode"]) > 0: # 如果设置了退出循环的脚本条件
  507. output = self.execute_code(int(node["parameters"]["breakMode"]) -1, node["parameters"]["breakCode"], node["parameters"]["breakCodeWaitTime"])
  508. code = get_output_code(output)
  509. if code <= 0:
  510. break
  511. except NoSuchElementException:
  512. print("Loop element not found: ", node["parameters"]["xpath"])
  513. print("找不到循环元素: ", node["parameters"]["xpath"])
  514. self.recordLog("pathNotFound: " + node["parameters"]["xpath"])
  515. except Exception as e:
  516. raise
  517. elif int(node["parameters"]["loopType"]) == 2: # 固定元素列表
  518. for path in node["parameters"]["pathList"].split("\n"): # 千万不要忘了分割!!
  519. try:
  520. element = self.browser.find_element(By.XPATH, path)
  521. for i in node["sequence"]: # 挨个执行操作
  522. self.executeNode(i, element, path, 0)
  523. if self.browser.current_window_handle != thisHandle: # 如果执行完一次循环之后标签页的位置发生了变化
  524. while True: # 一直关闭窗口直到当前标签页
  525. self.browser.close() # 关闭使用完的标签页
  526. self.browser.switch_to.window(self.browser.window_handles[-1])
  527. if self.browser.current_window_handle == thisHandle:
  528. break
  529. if self.history["index"] != thisHistoryLength and self.history[
  530. "handle"] == self.browser.current_window_handle: # 如果执行完一次循环之后历史记录发生了变化,注意当前页面的判断
  531. difference = thisHistoryLength - \
  532. self.history["index"] # 计算历史记录变化差值
  533. self.browser.execute_script(
  534. 'history.go(' + str(difference) + ')') # 回退历史记录
  535. if node["parameters"]["historyWait"] > 2: # 回退后要等待的时间
  536. time.sleep(node["parameters"]["historyWait"])
  537. else:
  538. time.sleep(2)
  539. self.Log("Change history back time or:",
  540. node["parameters"]["historyWait"])
  541. self.browser.execute_script('window.stop()')
  542. except NoSuchElementException:
  543. print("Loop element not found: ", path)
  544. print("找不到循环元素: ", path)
  545. self.recordLog("pathNotFound: " + path)
  546. continue # 循环中找不到元素就略过操作
  547. except Exception as e:
  548. raise
  549. if int(node["parameters"]["breakMode"]) > 0: # 如果设置了退出循环的脚本条件
  550. output = self.execute_code(int(node["parameters"]["breakMode"]) -1, node["parameters"]["breakCode"], node["parameters"]["breakCodeWaitTime"])
  551. code = get_output_code(output)
  552. if code <= 0:
  553. break
  554. elif int(node["parameters"]["loopType"]) == 3: # 固定文本列表
  555. textList = node["parameters"]["textList"].split("\n")
  556. for text in textList:
  557. self.recordLog("input: " + text)
  558. for i in node["sequence"]: # 挨个执行操作
  559. self.executeNode(i, text, "", 0)
  560. if int(node["parameters"]["breakMode"]) > 0: # 如果设置了退出循环的脚本条件
  561. output = self.execute_code(int(node["parameters"]["breakMode"]) -1, node["parameters"]["breakCode"], node["parameters"]["breakCodeWaitTime"])
  562. code = get_output_code(output)
  563. if code <= 0:
  564. break
  565. elif int(node["parameters"]["loopType"]) == 4: # 固定网址列表
  566. # tempList = node["parameters"]["textList"].split("\r\n")
  567. urlList = list(
  568. filter(isnull, node["parameters"]["textList"].split("\n"))) # 去空行
  569. # urlList = []
  570. # for url in tempList:
  571. # if url != "":
  572. # urlList.append(url)
  573. for url in urlList:
  574. self.recordLog("input: " + url)
  575. for i in node["sequence"]:
  576. self.executeNode(i, url, "", 0)
  577. if int(node["parameters"]["breakMode"]) > 0: # 如果设置了退出循环的脚本条件
  578. output = self.execute_code(int(node["parameters"]["breakMode"]) -1, node["parameters"]["breakCode"], node["parameters"]["breakCodeWaitTime"])
  579. code = get_output_code(output)
  580. if code <= 0:
  581. break
  582. elif int(node["parameters"]["loopType"]) <= 6: # 命令返回值
  583. while True: # do while循环
  584. if int(node["parameters"]["loopType"]) == 5: # JS
  585. output = self.execute_code(0, node["parameters"]["code"], node["parameters"]["waitTime"])
  586. elif int(node["parameters"]["loopType"]) == 6: # System
  587. output = self.execute_code(1, node["parameters"]["code"], node["parameters"]["waitTime"])
  588. code = get_output_code(output)
  589. if code <= 0:
  590. break
  591. for i in node["sequence"]: # 挨个执行操作
  592. self.executeNode(i, code, node["parameters"]["xpath"], 0)
  593. self.history["index"] = thisHistoryLength
  594. self.history["handle"] = self.browser.current_window_handle
  595. self.scrollDown(node["parameters"])
  596. # 打开网页事件
  597. def openPage(self, para, loopValue):
  598. time.sleep(2) # 打开网页后强行等待至少2秒
  599. if len(self.browser.window_handles) > 1:
  600. self.browser.switch_to.window(self.browser.window_handles[-1]) # 打开网页操作从第1个页面开始
  601. self.browser.close()
  602. self.browser.switch_to.window(self.browser.window_handles[0]) # 打开网页操作从第1个页面开始
  603. self.history["handle"] = self.browser.current_window_handle
  604. if para["useLoop"]:
  605. url = loopValue
  606. elif para["url"] != "about:blank":
  607. url = self.links[self.urlId]
  608. # clear output parameters
  609. for key in self.outputParameters:
  610. self.outputParameters[key] = ""
  611. else:
  612. url = list(filter(isnull, para["links"].split("\n")))[0]
  613. try:
  614. maxWaitTime = int(para["maxWaitTime"])
  615. except:
  616. maxWaitTime = 10 # 默认最大等待时间为10秒
  617. try:
  618. self.browser.set_page_load_timeout(maxWaitTime) # 加载页面最大超时时间
  619. self.browser.set_script_timeout(maxWaitTime)
  620. self.browser.get(url)
  621. self.Log('Loading page: ' + url)
  622. self.recordLog('Loading page: ' + url)
  623. except TimeoutException:
  624. self.Log('time out after set seconds when loading page: ' + url)
  625. self.recordLog('time out after set seconds when loading page: ' + url)
  626. self.browser.execute_script('window.stop()')
  627. try:
  628. self.history["index"] = self.browser.execute_script("return history.length")
  629. except TimeoutException:
  630. self.browser.execute_script('window.stop()')
  631. self.history["index"] = self.browser.execute_script("return history.length")
  632. self.scrollDown(para) # 控制屏幕向下滚动
  633. if self.containJudge:
  634. try:
  635. self.bodyText = self.browser.find_element(By.CSS_SELECTOR, "body").text
  636. self.Log('URL Page: ' + url)
  637. self.recordLog('URL Page: ' + url)
  638. except TimeoutException:
  639. self.Log('Time out after set seconds when getting body text: ' + url)
  640. self.recordLog('Time out after set seconds when getting body text:: ' + url)
  641. self.browser.execute_script('window.stop()')
  642. time.sleep(1)
  643. self.Log("Need to wait 1 second to get body text")
  644. # 再执行一遍
  645. self.bodyText = self.browser.find_element(By.CSS_SELECTOR, "body").text
  646. except Exception as e:
  647. self.Log(e)
  648. self.recordLog(str(e))
  649. # 键盘输入事件
  650. def inputInfo(self, para, loopValue):
  651. time.sleep(0.1) # 输入之前等待0.1秒
  652. self.Log("Wait 1 second before input")
  653. try:
  654. textbox = self.browser.find_element(By.XPATH, para["xpath"])
  655. # textbox.send_keys(Keys.CONTROL, 'a')
  656. # textbox.send_keys(Keys.BACKSPACE)
  657. self.execute_code(2, para["beforeJS"], para["beforeJSWaitTime"], textbox) # 执行前置JS
  658. # Send the HOME key
  659. textbox.send_keys(Keys.HOME)
  660. # Send the SHIFT + END key combination
  661. textbox.send_keys(Keys.SHIFT, Keys.END)
  662. # Send the DELETE key
  663. textbox.send_keys(Keys.DELETE)
  664. if para["useLoop"]:
  665. textbox.send_keys(loopValue)
  666. else:
  667. textbox.send_keys(para["value"])
  668. self.execute_code(2, para["afterJS"], para["afterJSWaitTime"], textbox) # 执行后置js
  669. # global bodyText # 每次执行点击,输入元素和打开网页操作后,需要更新bodyText
  670. self.bodyText = self.browser.find_element(By.CSS_SELECTOR, "body").text
  671. except:
  672. print("Cannot find input box element:" +
  673. para["xpath"] + ", please try to set the wait time before executing this operation")
  674. print("找不到输入框元素:" + para["xpath"] + ",请尝试在执行此操作前设置等待时间")
  675. self.recordLog("Cannot find input box element:" +
  676. para["xpath"] + "Please try to set the wait time before executing this operation")
  677. # 点击元素事件
  678. def clickElement(self, para, loopElement=None, clickPath="", index=0):
  679. time.sleep(0.1) # 点击之前等待0.1秒
  680. self.Log("Wait 0.1 second before clicking element")
  681. if para["useLoop"]: # 使用循环的情况下,传入的clickPath就是实际的xpath
  682. path = clickPath
  683. else:
  684. path = para["xpath"] # 不然使用元素定义的xpath
  685. try:
  686. maxWaitTime = int(para["maxWaitTime"])
  687. except:
  688. maxWaitTime = 10
  689. self.browser.set_page_load_timeout(maxWaitTime) # 加载页面最大超时时间
  690. self.browser.set_script_timeout(maxWaitTime)
  691. # 点击前对该元素执行一段JavaScript代码
  692. try:
  693. element = self.browser.find_element(By.XPATH, path)
  694. if para["beforeJS"] != "":
  695. self.execute_code(2, para["beforeJS"], para["beforeJSWaitTime"], element)
  696. except:
  697. print("Cannot find element:" +
  698. path + ", please try to set the wait time before executing this operation")
  699. print("找不到要点击的元素:" + path + ",请尝试在执行此操作前设置等待时间")
  700. self.recordLog("Cannot find element:" +
  701. path + ", please try to set the wait time before executing this operation")
  702. tempHandleNum = len(self.browser.window_handles) # 记录之前的窗口位置
  703. try:
  704. script = 'var result = document.evaluate(`' + path + \
  705. '`, document, null, XPathResult.ANY_TYPE, null);for(let i=0;i<arguments[0];i++){result.iterateNext();} result.iterateNext().click();'
  706. self.browser.execute_script(script, str(index)) # 用js的点击方法
  707. except TimeoutException:
  708. self.Log('time out after set seconds when loading clicked page')
  709. self.recordLog('time out after set seconds when loading clicked page')
  710. self.browser.execute_script('window.stop()')
  711. except Exception as e:
  712. self.Log(e)
  713. self.recordLog(str(e))
  714. # 点击前对该元素执行一段JavaScript代码
  715. try:
  716. if para["afterJS"] != "":
  717. element = self.browser.find_element(By.XPATH, path)
  718. self.execute_code(2, para["afterJS"], para["afterJSWaitTime"], element)
  719. except:
  720. print("Cannot find element:" + path)
  721. self.recordLog("Cannot find element:" +
  722. path + ", please try to set the wait time before executing this operation")
  723. print("找不到要点击的元素:" + path + ",请尝试在执行此操作前设置等待时间")
  724. if tempHandleNum != len(self.browser.window_handles): # 如果有新标签页的行为发生
  725. self.browser.switch_to.window(self.browser.window_handles[-1]) # 跳转到新的标签页
  726. self.history["handle"] = self.browser.current_window_handle
  727. try:
  728. self.history["index"] = self.browser.execute_script("return history.length")
  729. except TimeoutException:
  730. self.browser.execute_script('window.stop()')
  731. self.history["index"] = self.browser.execute_script("return history.length")
  732. else:
  733. try:
  734. self.history["index"] = self.browser.execute_script("return history.length")
  735. except TimeoutException:
  736. self.browser.execute_script('window.stop()')
  737. self.history["index"] = self.browser.execute_script("return history.length")
  738. # 如果打开了新窗口,切换到新窗口
  739. self.scrollDown(para) # 根据参数配置向下滚动
  740. if self.containJudge: # 有判断语句才执行以下操作
  741. # global bodyText # 每次执行点击,输入元素和打开网页操作后,需要更新bodyText
  742. try:
  743. self.bodyText = self.browser.find_element(By.CSS_SELECTOR, "body").text
  744. except TimeoutException:
  745. self.Log('time out after 10 seconds when getting body text')
  746. self.recordLog('time out after 10 seconds when getting body text')
  747. self.browser.execute_script('window.stop()')
  748. time.sleep(1)
  749. self.Log("wait one second after get body text")
  750. # 再执行一遍
  751. self.bodyText = self.browser.find_element(By.CSS_SELECTOR, "body").text
  752. # rt.end()
  753. except Exception as e:
  754. self.Log(e)
  755. self.recordLog(str(e))
  756. # rt.end()
  757. def get_content(self, p, element):
  758. content = ""
  759. # 先处理特殊节点类型
  760. if p["nodeType"] == 2:
  761. if element.get_attribute("href") != None:
  762. content = element.get_attribute("href")
  763. else:
  764. content = ""
  765. elif p["nodeType"] == 3:
  766. if element.get_attribute("value") != None:
  767. content = element.get_attribute("value")
  768. else:
  769. content = ""
  770. elif p["nodeType"] == 4: # 图片
  771. if element.get_attribute("src") != None:
  772. content = element.get_attribute("src")
  773. else:
  774. content = ""
  775. try:
  776. downloadPic = p["downloadPic"]
  777. except:
  778. downloadPic = 0
  779. if downloadPic == 1:
  780. download_image(content, "Data/" + self.saveName + "/")
  781. else: # 普通节点
  782. if p["contentType"] == 0:
  783. content = element.text
  784. elif p["contentType"] == 1: # 只采集当期元素下的文本,不包括子元素
  785. command = 'var arr = [];\
  786. var content = arguments[0];\
  787. for(var i = 0, len = content.childNodes.length; i < len; i++) {\
  788. if(content.childNodes[i].nodeType === 3){ \
  789. arr.push(content.childNodes[i].nodeValue);\
  790. }\
  791. }\
  792. var str = arr.join(" "); \
  793. return str;'
  794. content = self.browser.execute_script(command, element).replace(
  795. "\n", "").replace("\\s+", " ")
  796. elif p["contentType"] == 2:
  797. content = element.get_attribute('innerHTML')
  798. elif p["contentType"] == 3:
  799. content = element.get_attribute('outerHTML')
  800. elif p["contentType"] == 4:
  801. # 获取元素的背景图片地址
  802. bg_url = element.value_of_css_property('background-image')
  803. # 清除背景图片地址中的多余字符
  804. bg_url = bg_url.replace('url("', '').replace('")', '')
  805. content = bg_url
  806. elif p["contentType"] == 5:
  807. content = self.browser.current_url
  808. elif p["contentType"] == 6:
  809. content = self.browser.title
  810. elif p["contentType"] == 7:
  811. # 获取整个网页的高度和宽度
  812. height = self.browser.execute_script("return document.body.scrollHeight");
  813. width = self.browser.execute_script("return document.body.scrollWidth");
  814. # 调整浏览器窗口的大小
  815. self.browser.set_window_size(width, height)
  816. element.screenshot("Data/" + self.saveName + "/"+ str(time.time()) + ".png")
  817. elif p["contentType"] == 8:
  818. try:
  819. screenshot = element.screenshot_as_png
  820. screenshot_stream = io.BytesIO(screenshot)
  821. # 使用Pillow库打开截图,并转换为灰度图像
  822. image = Image.open(screenshot_stream).convert('L')
  823. # 使用Tesseract OCR引擎识别图像中的文本
  824. text = pytesseract.image_to_string(image, lang='chi_sim+eng')
  825. content = text
  826. except Exception as e:
  827. content = "OCR Error"
  828. 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")
  829. if sys.platform == "win32":
  830. print("要使用OCR识别功能,你需要安装Tesseract-OCR并将其添加到环境变量PATH中(添加后需重启EasySpider):https://blog.csdn.net/u010454030/article/details/80515501\nhttps://www.bilibili.com/video/BV1xz4y1b72D/")
  831. elif sys.platform == "darwin":
  832. print(e)
  833. print("注意以上错误,要使用OCR识别功能,你需要安装Tesseract-OCR并将其添加到环境变量PATH中(添加后需重启EasySpider):https://zhuanlan.zhihu.com/p/146044810")
  834. elif sys.platform == "linux":
  835. print(e)
  836. print("注意以上错误,要使用OCR识别功能,你需要安装Tesseract-OCR并将其添加到环境变量PATH中(添加后需重启EasySpider):https://zhuanlan.zhihu.com/p/420259031")
  837. else:
  838. print(e)
  839. print("注意以上错误,要使用OCR识别功能,你需要安装Tesseract-OCR并将其添加到环境变量PATH中(添加后需重启EasySpider):https://blog.csdn.net/u010454030/article/details/80515501\nhttps://www.bilibili.com/video/BV1xz4y1b72D/")
  840. elif p["contentType"] == 9:
  841. content = self.execute_code(2, p["JS"], p["JSWaitTime"], element)
  842. elif p["contentType"] == 10: # 下拉框选中的值
  843. try:
  844. select_element = Select(element)
  845. content = select_element.first_selected_option.get_attribute("value")
  846. except:
  847. content = ""
  848. elif p["contentType"] == 11: # 下拉框选中的文本
  849. try:
  850. select_element = Select(element)
  851. content = select_element.first_selected_option.text
  852. except:
  853. content = ""
  854. return content
  855. # 提取数据事件
  856. def getData(self, para, loopElement, isInLoop=True, parentPath="", index=0):
  857. for p in para["paras"]:
  858. content = ""
  859. if not (p["contentType"] == 5 or p["contentType"] == 6): # 如果不是页面标题或URL,去找元素
  860. try:
  861. if p["relative"]: # 是否相对xpath
  862. if p["relativeXPath"] == "": # 相对xpath有时候就是元素本身,不需要二次查找
  863. element = loopElement
  864. else:
  865. if p["relativeXPath"].find("//") >= 0: # 如果字串里有//即子孙查找,则不动语句
  866. full_path = "(" + parentPath + \
  867. p["relativeXPath"] + ")" + \
  868. "[" + str(index + 1) + "]"
  869. element = self.browser.find_element(By.XPATH, full_path)
  870. else:
  871. element = loopElement.find_element(By.XPATH,
  872. p["relativeXPath"][1:])
  873. else:
  874. element = self.browser.find_element(By.XPATH, p["relativeXPath"])
  875. except (NoSuchElementException, InvalidSelectorException): # 找不到元素的时候,使用默认值
  876. # print(p)
  877. try:
  878. content = p["default"]
  879. except Exception as e:
  880. content = ""
  881. self.outputParameters[p["name"]] = content
  882. try:
  883. if not self.dataNotFoundKeys[p["name"]]:
  884. print('Element %s not found with parameter name %s when extracting data, use default, this error will only show once' % (p["relativeXPath"], p["name"]))
  885. print("提取数据操作时,字段名 %s 对应XPath %s 未找到,使用默认值,本字段将不再重复报错" % (p["name"], p["relativeXPath"]))
  886. self.dataNotFoundKeys[p["name"]] = True
  887. self.recordLog('Element %s not found, use default' % p["relativeXPath"])
  888. except:
  889. pass
  890. continue
  891. except TimeoutException: # 超时的时候设置超时值
  892. self.Log('time out after set seconds when getting data')
  893. self.recordLog('time out after set seconds when getting data')
  894. self.browser.execute_script('window.stop()')
  895. if p["relative"]: # 是否相对xpath
  896. if p["relativeXPath"] == "": # 相对xpath有时候就是元素本身,不需要二次查找
  897. element = loopElement
  898. else:
  899. element = loopElement.find_element(By.XPATH,
  900. p["relativeXPath"][1:])
  901. else:
  902. element = self.browser.find_element(By.XPATH, p["relativeXPath"])
  903. # rt.end()
  904. else:
  905. element = self.browser.find_element(By.XPATH, "//body")
  906. try:
  907. self.execute_code(2, p["beforeJS"], p["beforeJSWaitTime"], element) # 执行前置js
  908. content = self.get_content(p, element)
  909. except StaleElementReferenceException: # 发生找不到元素的异常后,等待几秒重新查找
  910. self.recordLog('StaleElementReferenceException:'+p["relativeXPath"])
  911. time.sleep(3)
  912. try:
  913. if p["relative"]: # 是否相对xpath
  914. if p["relativeXPath"] == "": # 相对xpath有时候就是元素本身,不需要二次查找
  915. element = loopElement
  916. self.recordLog('StaleElementReferenceException:loopElement')
  917. else:
  918. element = loopElement.find_element(By.XPATH,
  919. p["relativeXPath"][1:])
  920. self.recordLog(
  921. 'StaleElementReferenceException:loopElement+relativeXPath')
  922. else:
  923. element = self.browser.find_element(
  924. By.XPATH, p["relativeXPath"])
  925. self.recordLog('StaleElementReferenceException:relativeXPath')
  926. content = self.get_content(p, element)
  927. except StaleElementReferenceException:
  928. self.recordLog('StaleElementReferenceException:'+p["relativeXPath"])
  929. continue # 再出现类似问题直接跳过
  930. self.outputParameters[p["name"]] = content
  931. self.execute_code(2, p["afterJS"], p["afterJSWaitTime"], element) # 执行后置JS
  932. line = []
  933. for value in self.outputParameters.values():
  934. line.append(value)
  935. print(value[:15], " ", end="")
  936. print("")
  937. self.OUTPUT.append(line)
  938. # rt.end()
  939. if __name__ == '__main__':
  940. config = {
  941. "id": [0],
  942. "saved_file_name": "",
  943. "user_data": False,
  944. "config_folder": "",
  945. "config_file_name": "config.json",
  946. "read_type": "remote",
  947. "headless": False,
  948. "server_address": "http://localhost:8074",
  949. "version": "0.3.1",
  950. }
  951. c = Config(config)
  952. print(c)
  953. options = Options()
  954. driver_path = "chromedriver.exe"
  955. import platform
  956. print(sys.platform, platform.architecture())
  957. option = webdriver.ChromeOptions()
  958. if not os.path.exists(os.getcwd()+"/Data"):
  959. os.mkdir(os.getcwd()+"/Data")
  960. if sys.platform == "darwin" and platform.architecture()[0] == "64bit":
  961. options.binary_location = "EasySpider.app/Contents/Resources/app/chrome_mac64.app/Contents/MacOS/Google Chrome"
  962. # MacOS需要用option而不是options!
  963. option.binary_location = "EasySpider.app/Contents/Resources/app/chrome_mac64.app/Contents/MacOS/Google Chrome"
  964. driver_path = "EasySpider.app/Contents/Resources/app/chromedriver_mac64"
  965. # options.binary_location = "chrome_mac64.app/Contents/MacOS/Google Chrome"
  966. # # MacOS需要用option而不是options!
  967. # option.binary_location = "chrome_mac64.app/Contents/MacOS/Google Chrome"
  968. # driver_path = os.getcwd()+ "/chromedriver_mac64"
  969. print(driver_path)
  970. elif os.path.exists(os.getcwd()+"/EasySpider/resources"): # 打包后的路径
  971. print("Finding chromedriver in EasySpider",
  972. os.getcwd()+"/EasySpider")
  973. if sys.platform == "win32" and platform.architecture()[0] == "32bit":
  974. options.binary_location = os.path.join(
  975. os.getcwd(), "EasySpider/resources/app/chrome_win32/chrome.exe") # 指定chrome位置
  976. driver_path = os.path.join(
  977. os.getcwd(), "EasySpider/resources/app/chrome_win32/chromedriver_win32.exe")
  978. elif sys.platform == "win32" and platform.architecture()[0] == "64bit":
  979. options.binary_location = os.path.join(
  980. os.getcwd(), "EasySpider/resources/app/chrome_win64/chrome.exe")
  981. driver_path = os.path.join(
  982. os.getcwd(), "EasySpider/resources/app/chrome_win64/chromedriver_win64.exe")
  983. elif sys.platform == "linux" and platform.architecture()[0] == "64bit":
  984. options.binary_location = "EasySpider/resources/app/chrome_linux64/chrome"
  985. driver_path = "EasySpider/resources/app/chrome_linux64/chromedriver_linux64"
  986. else:
  987. print("Unsupported platform")
  988. sys.exit()
  989. print("Chrome location:", options.binary_location)
  990. print("Chromedriver location:", driver_path)
  991. elif os.path.exists(os.getcwd()+"/../ElectronJS"):
  992. if os.getcwd().find("ElectronJS") >= 0: # 软件dev用
  993. print("Finding chromedriver in EasySpider",
  994. os.getcwd())
  995. option.binary_location = "chrome_win64/chrome.exe"
  996. driver_path = "chrome_win64/chromedriver_win64.exe"
  997. else: # 直接在executeStage文件夹内使用python easyspider_executestage.py时的路径
  998. print("Finding chromedriver in EasySpider",
  999. os.getcwd()+"/ElectronJS")
  1000. option.binary_location = "../ElectronJS/chrome_win64/chrome.exe" # 指定chrome位置
  1001. driver_path = "../ElectronJS/chrome_win64/chromedriver_win64.exe"
  1002. elif os.getcwd().find("ExecuteStage") >= 0: # 如果直接执行
  1003. print("Finding chromedriver in ./Chrome",
  1004. os.getcwd()+"/Chrome")
  1005. options.binary_location = "./Chrome/chrome.exe" # 指定chrome位置
  1006. # option.binary_location = "C:\\Users\\q9823\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe"
  1007. driver_path = "./Chrome/chromedriver.exe"
  1008. else:
  1009. options.binary_location = "./chrome.exe" # 指定chrome位置
  1010. driver_path = "./chromedriver.exe"
  1011. option.add_experimental_option(
  1012. 'excludeSwitches', ['enable-automation']) # 以开发者模式
  1013. # user_data_dir = r'' # 注意没有Default!
  1014. # options.add_argument('--user-data-dir='+p)
  1015. # 总结:
  1016. # 0. 带Cookie需要用userdatadir
  1017. # 1. chrome_options才是配置用户文件和chrome文件地址的正确选项
  1018. # 2. User Profile文件夹的路径是:C:\Users\用户名\AppData\Local\Google\Chrome\User Data不要加Default
  1019. # 3. 就算User Profile相同,chrome版本不同所存储的cookie信息也不同,也不能爬
  1020. # 4. TMALL如果一直弹出验证码,而且无法通过验证,那么需要在其他浏览器上用
  1021. if c.user_data:
  1022. with open(c.config_folder + c.config_file_name,"r", encoding='utf-8') as f:
  1023. config = json.load(f)
  1024. absolute_user_data_folder = config["absolute_user_data_folder"]
  1025. print("\nAbsolute_user_data_folder:",absolute_user_data_folder,"\n")
  1026. option.add_argument(f'--user-data-dir={absolute_user_data_folder}') # TMALL 反扒
  1027. option.add_argument("--profile-directory=Default")
  1028. if c.headless:
  1029. print("Headless mode")
  1030. print("无头模式")
  1031. option.add_argument("--headless")
  1032. options.add_argument("--headless")
  1033. # options.add_argument(
  1034. # '--user-data-dir=C:\\Users\\q9823\\AppData\\Local\\Google\\Chrome\\User Data') # TMALL 反扒
  1035. option.add_argument(
  1036. "--disable-blink-features=AutomationControlled") # TMALL 反扒
  1037. options.add_argument("--disable-blink-features=AutomationControlled") # TMALL 反扒
  1038. print(options)
  1039. threads = []
  1040. for i in c.id:
  1041. browser_t = webdriver.Chrome(
  1042. options=options, chrome_options=option, executable_path=driver_path)
  1043. thread = BrowserThread(browser_t, i, c.saved_file_name, c.read_type, c.server_address, c.version)
  1044. print("Thread with task id: ", i, " is created")
  1045. threads.append(thread)
  1046. thread.start()
  1047. for thread in threads:
  1048. thread.join()
  1049. for thread in threads:
  1050. thread.browser.quit()
  1051. print("Thread with task id: ", thread.id, " is closed")