通过selenium获取cookies(包括了短信认证和二维码认证两种方法)

准备工作:首选需要安装Chrome浏览器,然后根据浏览器版本,下载对应的chromedriver.exe
chromedriver.exe 下载地址:http://npm.taobao.org/mirrors/chromedriver/
获取到cookie之后就可以做很多事情了,比如和我之前的爬公司内网数据的代码结合起来,这样就不用手工登陆然后再手工复制cookie了
网上能够找到的代码都是把cookies保存到本地txt文档中,然后再提取出来,这样做可能是为了收集cookies库,但对于每次都需要动态码或二维码登陆的内网来说没有什么用处,所以我直接通过list-dict-list-str的过程直接把可用的cookie提取出来

from selenium import webdriver
import time

# 使用二维码扫描进入公司内网,同时获得原始cookies
def get_cookie_QRCode(url):
    driver = webdriver.Chrome()
    driver.get(url)
    time.sleep(3)
    button = driver.find_element_by_xpath(' // *[ @ id = "tipsButton"]')  # 等待3秒点击
    button.click()
    button = driver.find_element_by_xpath('//*[@id="tab_ul"]/li[4]/span') # 点击“二维码认证”
    button.click()
    time.sleep(10)
    cookies = driver.get_cookies()
    driver.quit()
    return cookies

#使用动态码进入公司内网,同时获得原始cookies
def get_cookie_DynamicCode(url):
    driver = webdriver.Chrome()
    driver.get(url)
    time.sleep(3)
    try:
        button = driver.find_element_by_xpath(' // *[ @ id = "tipsButton"]')  # 等待3秒点击
        button.click()
    except Exception as e:
        print(e)
    button = driver.find_element_by_xpath('//*[@id="tab_ul"]/li[2]/span') # 点击“动态码认证”
    button.click()
    element = driver.find_element_by_xpath('//*[@id="m_userid"]')  # 点击“用户名输入”
    element.send_keys('zhanglei1')
    element = driver.find_element_by_xpath('//*[@id="m_password"]')  # 点击“密码输入”
    element.send_keys(密码)
    button = driver.find_element_by_xpath('//*[@id="sendsms"]')  # 点击“发送动态码”
    button.click()
    element = driver.find_element_by_xpath('//*[@id="mobilesec"]')  # 点击“动态码输入”
    duanxin = input("请输入短信动态码:")
    element.send_keys(duanxin)
    button = driver.find_element_by_xpath('//*[@id="form3"]/table/tbody/tr[4]/td/input')  # 点击“登陆”
    button.click()
    cookies = driver.get_cookies() #这边获得的cookies是一个列表
    driver.quit()
    return cookies

#根据原始cookies进一步组合成能用的cookies
def add_cookie(cookies):
    items = []
    for i in range(len(cookies)):  #通过遍历cookies获得列表中的dict,然后再单独提取dict中的name和value数值并组合
        cookie_value = cookies[i]
        item = cookie_value['name'] +'=' + cookie_value['value']
        items.append(item)
    cookiestr = '; '.join(a for a in items) #这里需要注意的是“;”后面还有一个空格,所以这里其实是'; '
    return cookiestr

url = "http://www.sh.ctc.com/"
# cookie = get_cookie_QRCode(url)
cookie = get_cookie_DynamicCode(url)
add_cookie(cookie)

猜你喜欢

转载自blog.csdn.net/weixin_42029733/article/details/84144994