# -*- coding: utf-8 -*-
# @Time : 2020/3/27 7:02 AM
# @Author : wywinstonwy
# #@desc:
from selenium.webdriver.chrome.options import Options
from selenium import webdriver
from selenium.webdriver import ActionChains
import time
from PIL import Image
from io import BytesIO
import random
from settings import *
class BiliLogin():
name ='bili'
def __init__(self):
# 手动启动浏览器
"""
1.手动启动chrome。启动之前确保所有关闭
/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --remote-debugging-port=9222
:return:
"""
options = Options()
options.add_argument("--disable-extensions")
# options.add_experimental_option("debuggerAddress", "127.0.0.1:9222")
# options.add_experimental_option('excludeSwitches', ['enable-automation']) # 这里去掉
executable_path = '/Users/wangyun/Documents/PythonStudy/111Scrapy/source/chromedriver78'
# executable_path ='/Users/wangyun/Documents/chromedriver'
self.browser = webdriver.Chrome(executable_path=executable_path)
try:
self.browser.maximize_window()
except:
pass
def check_login(self):
try:
css = '.Avatar'
userimage = self.browser.find_element_by_class_name(css)
loginSucess = True
except:
loginSucess = False
return loginSucess
def login(self):
username = BiLI_USERNAME
password = BILI_PASSWORD
actions = ActionChains(self.browser)
url = 'https://passport.bilibili.com/login'
# url = 'https://www.zhihu.com/'
self.browser.get(url=url)
time.sleep(5)
isLogin = self.check_login()
login_count = 0
#检查如果没登录或者登录过期后再进行登录操作,尝试登陆1次
while isLogin ==False and login_count <1:
login_count = login_count+1
# actions.move_to_element(tableAction).click().perform()
# actions.move_to_element_with_offset(tableAction, 1, 1).click().perform()
# actions.move_by_offset(location['x'],location['y'])
time.sleep(1)
#输入前情况输入框,防止二次输入。
self.browser.find_element_by_id("login-username").clear()
self.browser.find_element_by_id("login-username").send_keys(username)
time.sleep(2)
# 清空浏览器的方法
# 清空浏览器输入框的第二种方式是全部选中重新数据
# browser.find_element_by_name("username").send_keys(Keys.CONTROL+'a')
self.browser.find_element_by_id("login-passwd").clear()
self.browser.find_element_by_id("login-passwd").send_keys(password)
self.browser.find_element_by_class_name("btn-login").click()
time.sleep(3)
image2 = self.crop_image('captcha2.png')
time.sleep(3)
self.browser.execute_script(
'document.querySelectorAll("canvas")[3].style=""')
time.sleep(3)
self.crop_image('captcha1.png')
#拖动图片
#根据偏移量获取移动轨迹
#开始加速,然后加速,生长曲线,加入随机变动
#先开始加速度增长,当到整体目标的3/4时候进行减速度
target = 100
track = []
current = 0
mid = target*(3/4)
t = 0.1
v = 0
while current <target:
if current <mid:
#加速度
a = random.randint(2,4)
else:
#减速度
a = -random.randint(6,7)
v0 =v
#当前速度
v = v0+a*t
#增长值
grow = v0*t +1/2*a*t*t
#当前增长的总数
current += grow
track.append(round(grow))
drag_elem = self.browser.find_element_by_xpath(
'*//div[@class="geetest_slider_button"]')
actions.click_and_hold(drag_elem).perform()
for i in range(50):
actions.move_to_element_with_offset(drag_elem, xoffset=i,
yoffset=0).perform()
isLogin = self.check_login()
if isLogin:
cookie_dict ={}
cookies = self.browser.get_cookies()
for cookie in cookies:
cookie_dict[cookie['name']] =cookie['value']
self.browser.close()
return cookie_dict
def crop_image(self,image_file_name):
time.sleep(2)
img = self.browser.find_element_by_css_selector("body > div.geetest_panel.geetest_wind > div.geetest_panel_box.geetest_no_logo.geetest_panelshowslide > div.geetest_panel_next > div > div.geetest_wrap > div.geetest_widget > div > a > div.geetest_canvas_img.geetest_absolute > div > canvas.geetest_canvas_slice.geetest_absolute")
location = img.location
size = img.size
left,top,bottom,right =location['x'],location['y'],location['y']+size['height'],location['x']+size['width']
print('验证码位置',left,top,bottom,right)
# screen_shot = self.browser.get_screenshot_as_file('bili.png')
screen_shot = self.browser.get_screenshot_as_png()
screen_shot = Image.open(BytesIO(screen_shot))
captcha = screen_shot.crop((int(left),int(top),int(right),int(bottom)))
captcha.save(image_file_name)
return captcha
def comare_image(image1,image2,i,j):
pixel1 =image1.load()[i,j]
pixel2 =image2.load()[i,j]
threshold = 60
if abs(pixel1[0] - pixel2[0]) <threshold and abs(pixel1[1] - pixel2[1]) and abs(pixel1[2] - pixel2[2]):
return True
return False
if __name__ =="__main__":
# bili = BiliLogin()
image1 = Image.open("captcha1.png")
image2 = Image.open("captcha2.png")
has_find = False
left = 60
for i in range(60, image2.size[0]):
if has_find:
break
for j in range(image2.size[1]):
#找到不相等的就退出循环。
if not comare_image(image1,image2,i,j):
left = i
has_find = True
break
left -=6
print(left)