easyspider_executestage_single.py 52 KB

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