python+selenium模擬京東登錄后台
import json from time import sleep from selenium import webdriver #from selenium.webdriver.common.keys import keys #初始化瀏覽器 driver = webdriver.Chrome(executable_path = "e:\\chromedriver") #定義全局遍變量url url = "https://www.jd.com" def login_coolie(): #打開瀏覽器 driver.get(url) # 瀏覽器最大化 driver.maximize_window() #定位登錄button driver.find_element_by_class_name("link-login").click() #定位賬戶登錄 driver.find_element_by_xpath('//a[text()="賬戶登錄"]').click() #定位賬號框,並輸入賬號 driver.find_element_by_xpath('//input[@name="loginname"]').send_keys("1850105xxxx") #定位密碼框,並輸入密碼 driver.find_element_by_xpath('//input[@type="password"]').send_keys("XXXXX") #點擊登錄button driver.find_element_by_xpath('//a[@id="loginsubmit"]').click() sleep(5) #需要手動滑動圖片,通過校驗 #獲取coolie my_coolie = driver.get_cookies() print(my_coolie) data_cookie = json.dumps(my_coolie) with open("jd_coolies","w") as fp: fp.write(data_cookie) #使用cookies def get_url_with_cookies(): # 訪問網站,清空舊cookies信息 driver.get(url) driver.delete_all_cookies() #獲取cookies文件 with open("jd_coolies","r") as fp: jd_cookies = fp.read() #加載cookies信息 jd_cookies_dict = json.loads(jd_cookies) for cookie in jd_cookies_dict: driver.add_cookie(cookie) #驗證是否登錄成功 driver.get(url) print(url) if __name__=="__main__": login_coolie() get_url_with_cookies()
