from jiance_varg import * def jiance_open_chrome(): ''' 启动浏览器 :return: ''' # 获取浏览器cookie user_data_dir = r'--user-data-dir=C:\Users\S2020\AppData\Local\Google\Chrome\User Data' # # 加载配置数据 option = webdriver.ChromeOptions() # option.add_argument('-ignore-certificate-errors') # option.add_argument('-ignore -ssl-errors') option.add_argument('--ignore-certificate-errors') #忽略CERT证书错误 option.add_argument('--ignore-ssl-errors') #忽略SSL错误 option.add_argument('--disable-gpu') option.add_argument('--ignore-certificate-errors-spki-list') option.add_argument('--ignore-urlfetcher-cert-requests') capability = option.to_capabilities() capability["acceptInsecureCerts"] = True capability['acceptSslCerts'] = True option.add_argument('log-level=2') option.add_argument(user_data_dir) browser = webdriver.Chrome(chrome_options=option,desired_capabilities=capability) # => 注意这里的参数 #browser = webdriver.Chrome() browser.get('https://www.duozhuayu.com/cart') browser.implicitly_wait(5) time.sleep(5) return browser def send_content(result): try: url = quchong_url data = {"name":result} headers = {"Content-Type":"application/json"} rsp = requests.post(url,json = data,headers = headers) return rsp.status_code except: return 500 def jiance_get_book_content(browser): ''' 获取有货数据 :param browser: :return: ''' sell_books = browser.find_elements_by_class_name("SelItem")[0:-1] books = [] for i in sell_books: if '已预订' in i.find_element_by_class_name("action").text: continue book_title = i.find_element_by_class_name("book-title").text middle_section = i.find_element_by_class_name("middle-section").text Price = i.find_element_by_class_name("Price").text action = i.find_element_by_class_name("action").text if '已锁定' not in action: books.append([book_title,middle_section,Price,action]) return books def jiance_zhifu(browser): sell_books = browser.find_elements_by_class_name("SelItem")[0:-1] books = [] for i in sell_books: book_title = i.find_element_by_class_name("book-title").text middle_section = i.find_element_by_class_name("middle-section").text Price = i.find_element_by_class_name("Price").text action = i.find_element_by_class_name("action").text if '支付未完成' not in action: books.append([book_title, middle_section, Price, action]) return books def deal_data(data1,data2): ''' 对比前后数据不一样的地方,查看品相,合格得返回,不合格得不处理 :param data1: :param data2: :return: ''' new_data = [] qty_good = ['品相良好','轻度污渍','轻度磨损或破损'] #需要支付的数据 for i in data2: if i not in data1 and i[1] in qty_good and i[0] not in xiadan_data and "支付未完成" not in i[3]: new_data.append(i) print(new_data) return new_data def new_order(browser,j): ''' 对应数据下单 :param browser: :return: ''' global xiadan_data #sell_books = browser.find_elements_by_class_name("SelItem")[0:-1] sell_books = browser.find_elements_by_class_name("SelItem") a = 0 order_data = [] print(len(sell_books)) for i in range(0,len(sell_books)): try: sell_books[i].find_element_by_class_name("book-title") except: continue if sell_books[i].find_element_by_class_name("book-title").text == j[0]: # print(1) if j[3] != '支付未完成,再次支付': action = sell_books[i].find_element_by_class_name("action") browser.execute_script('arguments[0].scrollIntoView(true)', action) action.click() # 设置等待 wait = WebDriverWait(browser, 5, 0.5) # 使用匿名函数 x = sell_books[i] #wait.until(lambda x: x.find_element_by_xpath("//*[contains(text(),'支付锁定款')]")) wait.until(lambda x: x.find_element_by_class_name("Button--clay")) time.sleep(0.5) browser.find_elements_by_class_name("Button-inner")[-1].click() wait.until(lambda x: x.find_element_by_class_name("Button--clay")) #wait.until(lambda x: x.find_elements_by_xpath("//*[contains(text(),'微信支付')]")) time.sleep(0.5) browser.find_elements_by_class_name("Button-inner")[-1].click() #sell_books[i].find_elements_by_xpath("//*[contains(text(),'微信支付')]")[-1].click() # time.sleep(1) # sell_books[i].find_element_by_class_name("Button--normal").click() # time.sleep(1) # sell_books[i].find_element_by_class_name("Button--normal").find_element_by_class_name("Button-inner").click() time.sleep(2) if not browser.find_elements_by_xpath("//*[contains(text(),'支付编号')]"): print("没获取到支付二维码,没抢到书") return False global erweima erweima = str(int(time.time())) + "erweima.jpg" browser.save_screenshot(erweima) browser.refresh() wait.until(lambda browser: browser.find_elements_by_class_name("SelItem")) time.sleep(3) sell_books = browser.find_elements_by_class_name("SelItem")[0:-1] a = 1 order_data.append(j) xiadan_data.append(j[0]) print(xiadan_data) print("处理数据结果:") if a == 0: print('无数据要处理') return False else: print(msg_data,end='') print("处理成功") return order_data # return data def send_dingding(server_msg): ''' 发送短信给主人 :return: ''' # 定义请求的URL timestamp = str(round(time.time() * 1000)) url = dingding_url secret = dingding_secret secret_enc = secret.encode('utf-8') string_to_sign = '{}\n{}'.format(timestamp, secret) string_to_sign_enc = string_to_sign.encode('utf-8') hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest() sign = quote_plus(base64.b64encode(hmac_code)) headers = {'Content-Type': 'application/json'} webhook = url + '×tamp=' + timestamp + '&sign=' + sign msg_data = '以下书籍已下单,请尽快核实付款:\n' for i in server_msg: msg_data = msg_data + i[0] + "\n" text = msg_data + "\n小闹新通知:您ip为"+ send_data + '的服务器所挂载的账号有新货到了,请尽快下单' data = { "msgtype": "text", "text": { "content": "%s" % (text) } } value = json.dumps(data) r = requests.post(webhook, value, headers=headers) def send_dingding_img(img_url): timestamp = str(round(time.time() * 1000)) url = dingding_url secret = dingding_secret secret_enc = secret.encode('utf-8') string_to_sign = '{}\n{}'.format(timestamp, secret) string_to_sign_enc = string_to_sign.encode('utf-8') hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest() sign = quote_plus(base64.b64encode(hmac_code)) headers = {'Content-Type': 'application/json'} webhook = url + '×tamp=' + timestamp + '&sign=' + sign # 构造消息体 message = { "msgtype": "markdown", "markdown": { "title": "test", # "text": "![screenshot](https://img.alicdn.com/tfs/TB1NwmBEL9TBuNjy1zbXXXpepXa-2400-1218.png) "text": "![screenshot](%s)"%(img_url) }, } response = requests.post(webhook, json=message,headers = headers) def handle_http_request(request): # 处理HTTP请求 response = "HTTP/1.1 200 OK\r\n" response += "Content-Type: text/plain\r\n" response += "\r\n" current_time = datetime.datetime.now() response += str(current_time) response += " success!" return response def zidongxiadan(): browser = jiance_open_chrome() # 设置等待 wait = WebDriverWait(browser, 5, 0.5) # 使用匿名函数 try: wait.until(lambda browser: browser.find_elements_by_class_name('SelItem')) #获取第一个数据列表 sale_books1 = jiance_get_book_content(browser) print("获取第一个数据列表") print(sale_books1) except: sale_books1 = [] good_data = deal_data([], sale_books1) print("获取两份数据表差异") print(good_data) if len(good_data) == 0: f = open("有书到货.txt", "a", encoding="utf-8") f.write("数据无差异") f.write("\n") for data in good_data: f = open("有书到货.txt", "a", encoding="utf-8") k = '数据差异:' for i in data: k = k + str(i) f.write(k) f.write("\n") # flag_data = new_order(browser, data) # 下单 try: zhifu_book = jiance_zhifu(browser) if len(zhifu_book) > 0: flag_data = new_order(browser, data) global xiadan_book xiadan_book = str(int(time.time())) + "book_xiadan.jpg" browser.save_screenshot(xiadan_book) f = open("有书到货.txt", "a", encoding="utf-8") f.write("下单成功") f.write("\n") else: flag_data = False # 下单 except: f = open("有书到货.txt", "a", encoding="utf-8") f.write("下单失败") f.write("\n") flag_data = False # 重置数据 time.sleep(2) browser.refresh() time.sleep(3) sale_books1 = jiance_get_book_content(browser) if flag_data: # 发送钉钉消息 status = send_content(data[0]) if status == 200: send_dingding(flag_data) print(erweima) print(xiadan_book) img_url = img_port + erweima send_dingding_img(img_url) img_url = img_port + xiadan_book send_dingding_img(img_url) print(data, end=' ') print("钉钉数据发送:处理成功") f = f = open("有书到货.txt", "a", encoding="utf-8") f.write("钉钉数据发送:处理成功") f.write("\n") time.sleep(2) browser.refresh() time.sleep(3) sale_books1 = jiance_get_book_content(browser) else: f = open("有书到货.txt", "a", encoding="utf-8") f.write("钉钉数据发送:处理失败") f.write("\n") time.sleep(2) browser.refresh() time.sleep(3) sale_books1 = jiance_get_book_content(browser) else: print("没发送钉钉消息") f = f = open("有书到货.txt", "a", encoding="utf-8") f.write("没发送钉钉消息") f.write("\n") sale_books1 = jiance_get_book_content(browser) server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.bind(('', 8000)) server_socket.listen(1) print("HTTP server is running at http://localhost:8000") #标志数据 while True: try: # 接受客户端连接 client_socket, client_address = server_socket.accept() # 接收HTTP请求 request = client_socket.recv(1024).decode() # 刷新浏览器,并下单记录信息。 print(request.split(' ')) # 处理HTTP请求并生成响应 response = handle_http_request(request) # 发送HTTP响应 client_socket.sendall(response.encode()) # 关闭客户端连接 client_socket.close() except: print("link fail, link again.") continue #判断请求信息是否与预期一致 if msg_data in request: #刷新浏览器,并获取新的数据,跟旧的数据进行对比 current_time = datetime.datetime.now() # f = open("有书到货.txt","a") f.write(str(current_time)) f.write("\n") browser.refresh() # 设置等待 wait = WebDriverWait(browser, 5, 0.5) # 使用匿名函数 try: #ime.sleep(4) #WebDriverWait(browser, 5, 0.5).until(lambda x:x.find_elements_by_class_name("SelItem")) wait.until(lambda browser: browser.find_elements_by_class_name('SelItem')) #获取新的数据 time.sleep(1) #获取第二次列表数据 sale_books2 = jiance_get_book_content(browser) print("获取第2个数据列表") print(sale_books2) except: sale_books2 = [] #跟旧数据进行对比,获取不一样得数据 if sale_books2 == []: continue #两份数据对比差距 good_data = deal_data(sale_books1,sale_books2) print("获取两份数据表差异") print(good_data) if len(good_data) == 0: f = open("有书到货.txt", "a",encoding="utf-8") f.write("数据无差异") f.write("\n") for data in good_data: f = open("有书到货.txt", "a",encoding="utf-8") k = '数据差异:' for i in data: k = k + str(i) f.write(k) f.write("\n") #flag_data = new_order(browser, data) #下单 try: zhifu_book = jiance_zhifu(browser) if len(zhifu_book) > 0: flag_data = new_order(browser, data) f = open("有书到货.txt", "a", encoding="utf-8") f.write("下单成功") f.write("\n") xiadan_book = str(int(time.time())) + "book_xiadan.jpg" browser.save_screenshot(xiadan_book) else: flag_data = False #下单 except: f = open("有书到货.txt", "a",encoding="utf-8") f.write("下单失败") f.write("\n") flag_data = False #重置数据 #time.sleep(2) #browser.refresh() #time.sleep(3) #sale_books1 = jiance_get_book_content(browser) if flag_data: #发送钉钉消息 status = send_content(data[0]) if status == 200: send_dingding(flag_data) print(erweima) print(xiadan_book) print(flag_data) img_url = img_port + erweima send_dingding_img(img_url) img_url = img_port + xiadan_book send_dingding_img(img_url) print(data,end=' ') print("钉钉数据发送:处理成功") f = f = open("有书到货.txt", "a",encoding="utf-8") f.write("钉钉数据发送:处理成功") f.write("\n") time.sleep(2) browser.refresh() time.sleep(3) sale_books1 = jiance_get_book_content(browser) else: print(data, end=' ') print("钉钉数据发送:处理失败,数据重复") f = f = open("有书到货.txt", "a", encoding="utf-8") f.write("钉钉数据发送:处理失败,数据重复") f.write("\n") time.sleep(2) browser.refresh() time.sleep(3) sale_books1 = jiance_get_book_content(browser) else: print("没发送钉钉消息") f = f = open("有书到货.txt", "a",encoding="utf-8") f.write("没发送钉钉消息") f.write("\n") sale_books1 = jiance_get_book_content(browser) def delete_files(directory, extension): for root, dirs, files in os.walk(directory): for file in files: if file.endswith('.' + extension): path = os.path.join(root, file) os.remove(path) print("已删除文件:", path) if __name__ == "__main__": #browser = jiance_open_chrome() delete_files('C://多抓鱼//整合版本', 'jpg') # '''启动浏览器端口监听''' # Handler = http.server.SimpleHTTPRequestHandler # # with socketserver.TCPServer(("", PORT), Handler) as httpd: # print("serving at port", PORT) # httpd.serve_forever() zidongxiadan()