easyspider_executestage.py 46 KB

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