1
0

easyspider_executestage.py 56 KB

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