我正在使用Selenium和Python登录页面,然后立即跳到同一选项卡中的另一页面。我需要保存页面的凭据,但是发生的情况是,当我移到新页面时它们会丢失。
我尝试了两件事-一是使用pickle.dump在以下代码中的input.send_keys(keys.ENTER)命令之后保存cookie,然后在加载新页面后加载相同的cookie。另一种是只加载保存cookie后创建的Firefox配置文件。
这是我的代码:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import pickle
from selenium.webdriver.firefox.webdriver import FirefoxProfile
profile = FirefoxProfile("C:\\Users\\ace\\AppData\\Local\\Mozilla\\Firefox\\Profiles\\l4piuit9.ace")
driver = webdriver.Firefox(profile)
driver.get("https://forums.the-elite.net/index.php?action=login")
# #handle the form data and log in by forcing an enter
inputElement1 = driver.find_element_by_name("cookieneverexp").click()
inputElement2 = driver.find_element_by_name("user")
inputElement2.send_keys('REMOVED')
inputElement3 = driver.find_element_by_name("passwrd")
inputElement3.send_keys('REMOVED')
inputElement3.send_keys(Keys.ENTER)
#save the cookies, they don't transfer over when navigating to a new page
#pickle.dump(driver.get_cookies(), open("elite.pkl", "wb"))
#new page / poll
driver.get("https://forums.the-elite.net/index.php?action=votelog;topic=22504")
#get the cookies
#cookies = pickle.load(open("elite.pkl", "rb"))
#for cookie in cookies:
# driver.add_cookie(cookie)
这些似乎都不起作用。我以为可能需要延迟,所以我将隐式等待时间设为10s,但这似乎没有什么作用。
这是什么原因,我该如何解决?
答案 0 :(得分:0)
您可以尝试以下方法:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import pickle
browser = webdriver.Chrome(executable_path = r'D:/Automation/chromedriver.exe')
browser.get("https://forums.the-elite.net/index.php?action=login")
wait = WebDriverWait(browser, 30)
browser.execute_script("window.scrollTo(0, -200)")
username = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "form#guest_form input[name='user']")))
username.send_keys('Removed')
password = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "form#guest_form input[name='passwrd']")))
password.send_keys('Removed')
password.send_keys(Keys.RETURN)
def save_cookie(browser, path):
with open(path, 'wb') as filehandler:
pickle.dump(browser.get_cookies(), filehandler)
def load_cookie(browser, path):
with open(path, 'rb') as cookiesfile:
cookies = pickle.load(cookiesfile)
for cookie in cookies:
driver.add_cookie(cookie)
请确保在加载Cookie后您刷新页面。