(我是在windows下進行實驗的)html
準備工做:python
一、安裝python環境。web
二、python安裝selenium插件(執行如下命令就行)。chrome
pip install seleniumwindows
三、Windows下配置webdriver chrome。瀏覽器
若是以上準備工做都作好了。cookie
那麼咱們就來編寫python腳本。less
腳本代碼以下:測試
# coding = utf-8 #模擬瀏覽器自動登陸yahoo郵箱 from selenium import webdriver from time import sleep from selenium.webdriver.chrome.options import Options #一下三行爲無頭模式運行,無頭模式不開啓瀏覽器,也就是在程序裏面運行的 chrome_options = Options() chrome_options.add_argument("--headless") browser = webdriver.Chrome(executable_path=(r'C:\Users\0923\AppData\Local\Google\Chrome\Application\chromedriver.exe'), options=chrome_options) # #若是不用上面三行,那麼就用下面這一行。運行的時候回自動的開啓瀏覽器,並在瀏覽器中自動運行,你能夠看到自動運行的過程 # browser = webdriver.Chrome(executable_path=(r'C:\Users\0923\AppData\Local\Google\Chrome\Application\chromedriver.exe')) #設置訪問連接 browser.get("https://www.yahoo.com") #點擊登陸按鈕 browser.find_element_by_id("uh-signin").click() #輸入用戶名 browser.find_element_by_id("login-username").send_keys("bjs***99") #點擊「下一步」 browser.find_element_by_id("login-signin").click() #等待10秒,以防讀取不到(#login-passwd)元素 sleep(10) #輸入密碼 browser.find_element_by_id("login-passwd").send_keys("Zf***234") #點擊signin按鈕 browser.find_element_by_id("login-signin").click() #獲取cookie cookie_items = browser.get_cookies() cookie_str = "" #組裝cookie字符串 for item_cookie in cookie_items: item_str = item_cookie["name"]+"="+item_cookie["value"]+"; " cookie_str += item_str print(item_cookie) #打印出來看一下 print(cookie_str) # sleep(5) # browser.get_screenshot_as_file('test.png') # browser.close() # print('test!')
運行以上代碼,會獲得以下結果,固然用戶名和密碼我該了一下,有須要的同窗本身註冊一個yahoo郵箱進行測試哈。spa
看到以上結果,表明咱們的代碼運行成功。