实战要求:
要求模拟qq一键登录的方式去登录CSDN,并将登录后的cookie保存下来,再用保存下来的cookie去模拟免登录方式去登录CSDN。
遇到问题:
- 选择qq一键登录,切换对应的frame,依然报无法定位到frame错误
- 使用cookie去模拟免登录,总是报 Cookie ‘domain’ mismatch 错误
原因分析
- 无法定位到frame,是因为本次测试使用qq一键登录时会打开新的标签,需要定位到新的标签窗口,才能定位到frame,否则会默认在第一个窗口定位,肯定找不到元素啦
- 使用cookie模拟免登录url应该是:https://www.csdn.net/,而不是:https://passport.csdn.net/login?code=public
完整代码
get_loginCookies.py:模拟qq一键登录,登录成功并保存cookie
from time import sleep
from selenium import webdriver
import json
if __name__ == '__main__':
driver = webdriver.Chrome()
driver.maximize_window()
driver.get('https://passport.csdn.net/login?code=public')
sleep(5)
frist_window = driver.current_window_handle
driver.find_element_by_css_selector('.icon-qq').click()
sleep(5)
all_windows = driver.window_handles
for handle in all_windows:
if handle != frist_window:
driver.switch_to.window(handle)
else:
pass
iframe = driver.find_element_by_xpath('//*[@id="ptlogin_iframe"]')
driver.switch_to.frame(iframe)
driver.find_element_by_xpath('/html/body/div[1]/div[4]/div[8]/div/a/span[4]').click()
sleep(5)
dictCookies = driver.get_cookies()
print(type(dictCookies))
jsonCookies = json.dumps(dictCookies)
with open('csdn_cookies.txt', 'w') as f:
f.write(jsonCookies)
print('cookies保存成功!')
driver.quit()
test_loginCSDN.py:使用保存的cookie模拟免登录
from selenium import webdriver
import json
def openCSDN():
driver = webdriver.Chrome()
driver.maximize_window()
driver.get('https://www.csdn.net/')
return driver
def log_CSDN(driver):
with open('csdn_cookies.txt', 'r', encoding='utf8') as f:
listCookies = json.loads(f.read())
print(listCookies)
for cookie in listCookies:
driver.add_cookie(cookie)
driver.refresh()
if __name__ == '__main__':
driver = openCSDN()
log_CSDN(driver)
|