代码:
# 贴吧图文写入cookies # 20210114把CHOME_DRIVER_DIR的目录加入进来的 import json import time from selenium import webdriver # 定义常量 BAIDU_USERNAME = 'xxx' BAIDU_PASSWORD = 'xxx' BAIDU_LOGIN_URL = 'https://tieba.baidu.com/home/creative/publish' BAIDU_COOKIES_FILE_NAME = 'C:\info\tieba_user_cookies01.txt' CHROME_DRIVER_DIR = 'C:\chromedriver_win32\chromedriver.exe' # 登录贴吧 driver = webdriver.Chrome(CHROME_DRIVER_DIR) driver.get(BAIDU_LOGIN_URL) time.sleep(5) # 开始登陆 driver.find_element_by_xpath('//*[@id="TANGRAM__PSP_4__footerULoginBtn"]').click() time.sleep(3) driver.find_element_by_xpath('//*[@id="TANGRAM__PSP_4__userName"]').send_keys(BAIDU_USERNAME) time.sleep(3) driver.find_element_by_xpath('//*[@id="TANGRAM__PSP_4__password"]').send_keys(BAIDU_PASSWORD) time.sleep(3) driver.find_element_by_xpath('//*[@id="TANGRAM__PSP_4__submit"]').click() time.sleep(60) # 读取cookies写入 driver.refresh() # 有个bug就是有时候这个refresh一直是卡主的 cookies_dict = driver.get_cookies() cookies_json = json.dumps(cookies_dict) with open(BAIDU_COOKIES_FILE_NAME, 'w') as f: f.write(cookies_json) print(cookies_json) print('Cookies写入文件ok了')