loginWeibo自制模块:使用selenium模拟登陆微博并获取cookie

(一)编程环境
操作系统:Win 10
编程语言:Python 3.7

(二)安装selenium
这里使用selenium实现。
如果没有安装过python的selenium库,则安装命令如下
pip install selenium
(三)下载ChromeDriver
因为selenium要用到浏览器的驱动,这里我用的是Google Chrome浏览器,所以要先下载ChromeDriver.exe并放到C:\Program Files (x86)\Google\Chrome\Application\目录下。
注意,放到别的目录下也行,只要在代码里填上正确的路径即可。

from selenium import webdriver
import time
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

def loginWeibo(username, password,url='https://passport.weibo.cn/signin/login',show=False,find_cookie=True):
    #默认展示关,寻找cookie开
    if show : driver = webdriver.Chrome(r"C:\Users\Administrator\Desktop\工具\chromedriver.exe")
    #这里需要更改为你的路径
    else:
        option=webdriver.ChromeOptions()
        option.add_argument('headless') # 设置option
        driver = webdriver.Chrome(r"C:\Users\Administrator\Desktop\工具\chromedriver.exe",options=option)  # 调用带参数的谷歌浏览器    
    driver.get(url)
    print('正在加载界面....')
    time.sleep(1)
    try:
        element = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.ID, "loginAction")))
    finally :
        driver.find_element_by_id("loginName").send_keys(username)
        driver.find_element_by_id("loginPassword").send_keys(password)
        driver.find_element_by_id("loginAction").click()
        print('已登录,正在获取cookie....')
    time.sleep(1)

    if find_cookie:        
        try:
            element = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.NAME, "viewport")))
        finally :
            cookies = driver.get_cookies()
            cookie_list = []
            for dict in cookies:
                cookie = dict['name'] + '=' + dict['value']
                cookie_list.append(cookie)
            cookie = ';'.join(cookie_list)
            print('获取cookie成功')
    else : cookie=False
    driver.close()
    return cookie

if __name__ == '__main__':    
    pass
    cookie=loginWeibo('username','password',url)
原创文章 27 获赞 24 访问量 2万+

猜你喜欢

转载自blog.csdn.net/u013289615/article/details/89306569