基于selenium模块自动登录boss直聘
import time
from PIL import Image
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver import ChromeOptions, ActionChains
from selenium.webdriver.common.by import By
from practiceproject.spiders.chaojiying import get_coord
# 定义函数,从selenium截取的整个网页图片里截取验证码区域的图片,location是验证码区域坐标,size是验证码区域大小
def get_bossyzm(location, size):
try:
im = Image.open('boss_login.png')
rangle = (int(location['x']),
int(location['y']),
int(location['x']) + int(size['width']),
int(location['y']) + int(size['height']),
)
print(rangle)
frame = im.crop(rangle)
# 保存到本地
frame.save('boss_yzm.png')
print('截取成功')
except Exception as e:
print('本地截取失败', e.__class__, e)
# 设置chrom浏览器无头模式的参数
chrom_options = Options()
chrom_options.add_argument('--headless')
chrom_options.add_argument('--disable-gpu')
# 设置chrom浏览器无法检测到selenium的参数
option = ChromeOptions()
option.add_experimental_option('excludeSwitches', ['enable-automation'])
# boss登录网址
url = 'https://login.zhipin.com/?ka=header-login'
if __name__ == '__main__':
# 不设置无头模式,便于观察
driver = webdriver.Chrome(options=option)
# 发起请求
driver.get(url)
# 窗口最大化
driver.maximize_window()
# 隐式等待10s
driver.implicitly_wait(5)
# 输入用户名和密码
driver.find_element(By.XPATH,
'//form[@action="/wapi/zppassport/login/accountV2"]//div/span/input[@name="account"]'
).click()
# 这里输入账号
driver.find_element(By.XPATH,
'//form[@action="/wapi/zppassport/login/accountV2"]//div/span/input[@name="account"]'
).send_keys('username')
driver.implicitly_wait(2)
driver.find_element(By.XPATH,
'//form[@action="/wapi/zppassport/login/accountV2"]//div/span/input[@name="password"]'
).click()
# 这里输入密码
driver.find_element(By.XPATH,
'//form[@action="/wapi/zppassport/login/accountV2"]//div/span/input[@name="password"]'
).send_keys('password')
driver.implicitly_wait(2)
# 点击生成验证码按钮
driver.find_element(By.XPATH, '//div[@class="verify-init-btn"]').click()
# 获取验证码图片区域坐标及大小
time.sleep(3)
yzm = driver.find_element(By.XPATH, '//div[@class="geetest_fullpage_click_box"]')
yzm_location = driver.find_element(By.XPATH, '//div[@class="geetest_fullpage_click_box"]').location
yzm_size = driver.find_element(By.XPATH, '//div[@class="geetest_fullpage_click_box"]').size
# 保存当前浏览器界面
driver.save_screenshot('boss_login.png')
# 使用PIL模块根据坐标和大小截取验证码图片
print(yzm_location, yzm_size, '坐标,大小')
get_bossyzm(yzm_location, yzm_size)
# 将验证码图片发送到超级鹰,获取返回坐标
result = get_coord('boss_yzm.png')
# 遍历结果集分别点击对应坐标
for i in result:
action = ActionChains(driver)
action.move_to_element_with_offset(yzm, i[0], i[1]).click().perform()
# 这里使用find_element()方法点击确认按钮的话会报错无法找到元素,暂时还不知道什么原因,所以就直接根据坐标来使用动作链操作了
action = ActionChains(driver)
action.move_to_element_with_offset(yzm, 290, 420).click().perform()
time.sleep(5)
# 点击登录按钮
driver.find_element(By.XPATH,
'//form[@action="/wapi/zppassport/login/accountV2"]/div[@class="form-btn"]/button').click()
# driver.quit()
版权声明:本文为wcw_____原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。