将新的Cookie添加到cookies.sqlite

时间:2019-01-14 14:24:16

标签: python-3.x firefox selenium-webdriver cookies

代码逻辑:

  1. Webdriver从常规的Firefox继承所有设置和cookie 浏览器。
  2. 此网络驱动程序用于访问提供以下内容的新网站 新的Cookie。

所以问题是如何将这些新的cookie添加回cookies.sqlite 而没有 摆弄sql插入语句,或者是否有生成新方法的方法cookies.sqlite文件将包含新旧Cookie?贝娄是我尝试使用带有插入语句的方法的代码,但是我真的不喜欢它,因为cookies.sqlite文件中的cookie和get_cookies()方法返回的cookie具有不同的格式。

from selenium import webdriver
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
import os.path
import shutil
import time
import sqlite3

original_profile_dir = 'C:/Users/hocke/AppData/Roaming/Mozilla/Firefox/Profiles/x9fhjo47.default'

print ('creating profile')
profile = FirefoxProfile(profile_directory=original_profile_dir)

print ('Profile dir: %s' % profile.profile_dir)
profile.set_preference("general.useragent.override", 'bot')

print ('updating prefs')
profile.update_preferences()

print ('creating browser')
browser = webdriver.Firefox(firefox_profile=profile)

print ('loading page')
browser.get('http://ya.ru') # 'www.flashexample.com/'
time.sleep(2)

cookies_file = profile.profile_dir + '/cookies.sqlite'
try:
    conn = sqlite3.connect(cookies_file )
    cur = conn.cursor()
    cur.execute("SELECT * FROM moz_cookies")
##    cur.execute("SELECT name FROM sqlite_master WHERE type='table'")
    rows = cur.fetchall()
    for row in rows:
        print(row)

    cursor = conn.execute('select * from moz_cookies')
    names = list(map(lambda x: x[0], cursor.description))
    print(names)

      # cookies.sqlite moz_cookies table columns
##    ['id', 'baseDomain', 'originAttributes',
##     'name', 'value', 'host', 'path', 'expiry',
##     'lastAccessed', 'creationTime', 'isSecure',
##     'isHttpOnly', 'inBrowserElement', 'sameSite']

      # example of a cookie found in cookies.sqlite database
##    (8, 'mozilla.org', '', '_gat', '1', '.mozilla.org', '/', 1547430227, 1547430167201000, 1547430167201000, 0, 0, 0, 0)

      # example of a cookie returned by get_cookies() method
##    {'name': 'yandexuid', 'value': '8652085301547430444', 'path': '/',
##     'domain': '.ya.ru',
##     'secure': False,
##     'httpOnly': False,
##     'expiry': 1862790444}

    sql = "INSERT INTO moz_cookies VALUES%s"
    for cookie in browser.get_cookies():
        print(cookie)
        cur.execute(sql % cookie) # code intentionally fails here
except Exception as e:
    print(e)
    pass

browser.close()
time.sleep(2)

print('backup cookies')
for name in ('cookies.sqlite', 'webdriver-py-profilecopy/cookies.sqlite'):
    cookies_file = os.path.join(profile.profile_dir, name)
    if os.path.exists(cookies_file):
        print ('found cookies file %s' % cookies_file)
        target = os.path.join(original_profile_dir, 'cookies.sqlite')
        print ('%s --> %s' % (cookies_file, target))
        shutil.copy(cookies_file, target)
        break

0 个答案:

没有答案