Python + Selenium WebDriver를 사용하여 쿠키를 저장하고 로드하는 방법
파이썬의 셀레늄 웹드라이버에 있는 모든 쿠키를 .txt 파일에 저장한 다음 나중에 로드하려면 어떻게 해야 합니까?
설명서에는 getCookies 기능에 대한 설명이 거의 없습니다.
피클을 사용하여 현재 쿠키를 Python 개체로 저장할 수 있습니다.예:
import pickle
import selenium.webdriver
driver = selenium.webdriver.Firefox()
driver.get("http://www.google.com")
pickle.dump(driver.get_cookies(), open("cookies.pkl", "wb"))
나중에 다시 추가합니다.
import pickle
import selenium.webdriver
driver = selenium.webdriver.Firefox()
driver.get("http://www.google.com")
cookies = pickle.load(open("cookies.pkl", "rb"))
for cookie in cookies:
driver.add_cookie(cookie)
세션마다 쿠키가 필요할 때 다른 방법이 있습니다.폴더를 프로파일로 사용하려면 Chrome 옵션 user-data-dir를 사용합니다.실행:
# You need to: from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("user-data-dir=selenium")
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get("www.google.com")
여기서 사람의 상호 작용을 확인하는 로그인을 수행할 수 있습니다.이 폴더로 웹 드라이버를 시작할 때마다 필요한 쿠키가 모두 들어 있습니다.또한 수동으로 Extensions를 설치하고 모든 세션에 포함시킬 수 있습니다.
두 번째로 실행하면 모든 쿠키가 표시됩니다.
# You need to: from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("user-data-dir=selenium")
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get("www.google.com") # Now you can see the cookies, the settings, extensions, etc., and the logins done in the previous session are present here.
장점은 다른 설정과 쿠키를 가진 여러 폴더를 사용할 수 있다는 것입니다. 쿠키를 로드, 언로드, 확장 설치 및 제거, 설정 변경, 코드를 통한 로그인 변경 등이 필요하지 않으므로 프로그램 중단에 대한 논리를 가질 수 없습니다.
또한, 이것은 코드로 모든 것을 해야 하는 것보다 더 빠릅니다.
현재 도메인에 대한 쿠키만 추가할 수 있습니다.
Google 계정에 쿠키를 추가하려면 다음을 수행합니다.
browser.get('http://google.com')
for cookie in cookies:
browser.add_cookie(cookie)
Roel Van de Par가 작성한 코드를 약간 수정했습니다. 모든 공은 그에게 있습니다.Windows에서 사용하고 있으며 쿠키 설정 및 추가 모두에서 완벽하게 작동합니다.
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("--user-data-dir=chrome-data")
driver = webdriver.Chrome('chromedriver.exe',options=chrome_options)
driver.get('https://web.whatsapp.com') # Already authenticated
time.sleep(30)
Eduard Florinescu의 답변을 기반으로 하지만 새로운 코드와 누락된 가져오기가 추가되었습니다.
$ cat work-auth.py
#!/usr/bin/python3
# Setup:
# sudo apt-get install chromium-chromedriver
# sudo -H python3 -m pip install selenium
import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("--user-data-dir=chrome-data")
driver = webdriver.Chrome('/usr/bin/chromedriver',options=chrome_options)
chrome_options.add_argument("user-data-dir=chrome-data")
driver.get('https://www.somedomainthatrequireslogin.com')
time.sleep(30) # Time to enter credentials
driver.quit()
$ cat work.py
#!/usr/bin/python3
import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("--user-data-dir=chrome-data")
driver = webdriver.Chrome('/usr/bin/chromedriver',options=chrome_options)
driver.get('https://www.somedomainthatrequireslogin.com') # Already authenticated
time.sleep(10)
driver.quit()
이상적으로 디렉터리를 복사하지 않는 것이 좋습니다. 하지만 이것은 매우 어렵습니다.
또한.
- C#을 사용하여 Selenium WebDriver의 기존 Firefox 프로필을 사용할 수 없습니다(아래 솔루션과 유사한 솔루션).
파이어폭스의 "" ""와 함).user-data-dir(사용자 데이터 디렉토리)(Chrome에서 디렉토리를 수동으로 복사합니다.)다른 방법을 찾을 수 없었습니다.):
리눅스에서 테스트되었습니다.
짧은 버전:
- 프로필 저장 방법
driver.execute_script("window.close()")
time.sleep(0.5)
currentProfilePath = driver.capabilities["moz:profile"]
profileStoragePath = "/tmp/abc"
shutil.copytree(currentProfilePath, profileStoragePath,
ignore_dangling_symlinks=True
)
- 프로필 로드 방법
driver = Firefox(executable_path="geckodriver-v0.28.0-linux64",
firefox_profile=FirefoxProfile(profileStoragePath)
)
긴 버전(작동하는 시연 및 많은 설명 포함 - 코드의 주석 참조)
코드는 다음을 사용합니다.localStorage시연용이지만 쿠키와도 작동합니다.
#initial imports
from selenium.webdriver import Firefox, FirefoxProfile
import shutil
import os.path
import time
# Create a new profile
driver = Firefox(executable_path="geckodriver-v0.28.0-linux64",
# * I'm using this particular version. If yours is
# named "geckodriver" and placed in system PATH
# then this is not necessary
)
# Navigate to an arbitrary page and set some local storage
driver.get("https://DuckDuckGo.com")
assert driver.execute_script(r"""{
const tmp = localStorage.a; localStorage.a="1";
return [tmp, localStorage.a]
}""") == [None, "1"]
# Make sure that the browser writes the data to profile directory.
# Choose one of the below methods
if 0:
# Wait for some time for Firefox to flush the local storage to disk.
# It's a long time. I tried 3 seconds and it doesn't work.
time.sleep(10)
elif 1:
# Alternatively:
driver.execute_script("window.close()")
# NOTE: It might not work if there are multiple windows!
# Wait for a bit for the browser to clean up
# (shutil.copytree might throw some weird error if the source directory changes while copying)
time.sleep(0.5)
else:
pass
# I haven't been able to find any other, more elegant way.
#`close()` and `quit()` both delete the profile directory
# Copy the profile directory (must be done BEFORE driver.quit()!)
currentProfilePath = driver.capabilities["moz:profile"]
assert os.path.isdir(currentProfilePath)
profileStoragePath = "/tmp/abc"
try:
shutil.rmtree(profileStoragePath)
except FileNotFoundError:
pass
shutil.copytree(currentProfilePath, profileStoragePath,
ignore_dangling_symlinks=True # There's a lock file in the
# profile directory that symlinks
# to some IP address + port
)
driver.quit()
assert not os.path.isdir(currentProfilePath)
# Selenium cleans up properly if driver.quit() is called,
# but not necessarily if the object is destructed
# Now reopen it with the old profile
driver=Firefox(executable_path="geckodriver-v0.28.0-linux64",
firefox_profile=FirefoxProfile(profileStoragePath)
)
# Note that the profile directory is **copied** -- see FirefoxProfile documentation
assert driver.profile.path!=profileStoragePath
assert driver.capabilities["moz:profile"]!=profileStoragePath
# Confusingly...
assert driver.profile.path!=driver.capabilities["moz:profile"]
# And only the latter is updated.
# To save it again, use the same method as previously mentioned
# Check the data is still there
driver.get("https://DuckDuckGo.com")
data = driver.execute_script(r"""return localStorage.a""")
assert data=="1", data
driver.quit()
assert not os.path.isdir(driver.capabilities["moz:profile"])
assert not os.path.isdir(driver.profile.path)
작동하지 않는 것:
- 초기화
Firefox(capabilities={"moz:profile": "/path/to/directory"})드라이버를 연결할 수 없습니다. options=Options(); options.add_argument("profile"); options.add_argument("/path/to/directory"); Firefox(options=options)상기와 같은
이것은 제가 Windows에서 사용했던 코드입니다.그건 효과가 있다.
for item in COOKIES.split(';'):
name,value = item.split('=', 1)
name=name.replace(' ', '').replace('\r', '').replace('\n', '')
value = value.replace(' ', '').replace('\r', '').replace('\n', '')
cookie_dict={
'name':name,
'value':value,
"domain": "", # Google Chrome
"expires": "",
'path': '/',
'httpOnly': False,
'HostOnly': False,
'Secure': False
}
self.driver_.add_cookie(cookie_dict)
다음 방법을 사용해 보십시오.
import pickle
from selenium import webdriver
driver = webdriver.Chrome(executable_path="chromedriver.exe")
URL = "SITE URL"
driver.get(URL)
sleep(10)
if os.path.exists('cookies.pkl'):
cookies = pickle.load(open("cookies.pkl", "rb"))
for cookie in cookies:
driver.add_cookie(cookie)
driver.refresh()
sleep(5)
# check if still need login
# if yes:
# write login code
# when login success save cookies using
pickle.dump(driver.get_cookies(), open("cookies.pkl", "wb"))
이 코드를 사용하여 Google Facebook 등과 같은 웹 사이트의 로그인 세션을 저장합니다.
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import undetected_chromedriver as uc
options = webdriver.ChromeOptions()
options.add_argument("user-data-dir=C:/Users/salee/AppData/Local/Google/Chrome/User Data/Profile 1")
browser = uc.Chrome(use_subprocess=True,Options=options)
저의 경우, 수락된 답변이 거의 다 왔습니다.
위의 답변에 운이 없는 사람들을 위해, 당신은 제 방법을 시도하는 것을 환영합니다.
코딩을 시작하기 전에 웹 사이트에서 인증에 쿠키를 사용하고 있는지 확인합니다.
단계:
- 브라우저를 열고(여기서 크롬을 사용하고 있습니다) 웹 사이트에 로그인합니다.
- 쿠키 값을 확인하는 방법을 알아보려면 이 웹 사이트로 이동합니다.
- 익명 모드에서 다른 브라우저를 열고 웹 사이트로 이동합니다(이 단계에서는 웹 사이트에서 로그인 페이지를 표시해야 함).
- 그에 따라 첫 번째 브라우저 쿠키 값으로 쿠키 값을 수정합니다(첫 번째 브라우저는 웹 사이트에 인증되어야 함).
- 로그인 페이지를 지나야 하는 익명 모드 브라우저를 새로 고칩니다.
위의 단계는 쿠키를 추가하여 웹 사이트에 인증할 수 있는지 확인하는 데 사용된 방법은 다음과 같습니다.
이제 코딩 부분인데, 인정된 답과 거의 같습니다.인정된 답변에 대한 유일한 문제는 결국 쿠키의 수가 두 배가 되었다는 것입니다.
피클.덤프 부분은 저에게 아무런 문제가 없기 때문에 쿠키 추가 부분으로 바로 넘어가겠습니다.
import pickle
import selenium.webdriver
driver = selenium.webdriver.Chrome()
driver.get("http://your.website.com")
cookies = pickle.load(open("cookies.pkl", "rb"))
# the reason that I delete the cookies is because I found duplicated cookies by inspect the cookies with browser like step 2
driver.delete_all_cookies()
for cookie in cookies:
driver.add_cookie(cookie)
driver.refresh()
2단계를 사용하여 코드로 추가한 쿠키가 제대로 작동하는지 확인할 수 있습니다.
도움이 되길 바랍니다.
여기 대부분의 답은 쿠키를 절이는 것인데, 제가 먹어봤는데 제대로 작동하지 않았습니다.쿠키의 응답을 텍스트 파일에 저장하고 필요할 때 로드할 수 있습니다.
웹사이트에 접속하여 로그인하거나 쿠키와 관련된 다른 활동을 하기
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("https://google.com")
쿠키 저장
with open("cookies.txt", "r") as f:
cookies = eval(f.read())
테스트하려면 드라이버를 닫았다가 다시 열고 쿠키를 로드합니다.
driver.quit()
driver = webdriver.Chrome()
driver.get("https://google.com")
쿠키 로드
for cookie in cookies:
driver.add_cookie(cookie)
변경 사항을 반영하여 새로 고침
driver.refresh()
언급URL : https://stackoverflow.com/questions/15058462/how-to-save-and-load-cookies-using-python-selenium-webdriver
'programing' 카테고리의 다른 글
| 최대 절전 모드에서 Oracle XMLType 열 사용 (0) | 2023.06.11 |
|---|---|
| 왜 'eval'을 사용하는 것이 나쁜 관행입니까? (0) | 2023.06.06 |
| 레일 위에서 루비 배우기 (0) | 2023.06.06 |
| 여러 값에 대한 Firestore 검색 배열 포함 (0) | 2023.06.06 |
| 오류: Gdal이 설치되어 있지만 R 종속 패키지를 설치하는 동안 gdal-config를 찾을 수 없습니다. (0) | 2023.06.06 |