Python + Selenium WebDriver를 사용하여 쿠키를 저장하고로드하는 방법
Python의 Selenium WebDriver에있는 모든 쿠키를 txt 파일에 저장 한 다음 나중에로드하려면 어떻게해야합니까? 문서는 getCookies 함수에 대해 많은 것을 말하지 않습니다.
pickle을 사용하여 현재 쿠키를 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을 사용하십시오.
chrome_options = Options()
chrome_options.add_argument("user-data-dir=selenium")
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get("www.google.com")
여기에서 사람의 상호 작용을 확인하는 로그인을 수행 할 수 있습니다.이 작업을 수행 한 다음 모든 것이 거기에있는 폴더로 Webdriver를 시작할 때마다 필요한 쿠키를 수행합니다. 또한 확장을 수동으로 설치하고 모든 세션에서 사용할 수 있습니다. 두 번째로 실행하면 모든 쿠키가 있습니다.
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.
장점은 다른 설정과 쿠키가있는 여러 폴더를 사용할 수 있다는 것입니다. 확장 프로그램은로드, 쿠키 언로드, 확장 설치 및 제거, 설정 변경, 코드를 통한 로그인 변경 등이 필요하지 않으므로 프로그램이 중단되는 논리를 가질 방법이 없습니다. etc 또한 이것은 코드로 모든 것을 수행하는 것보다 빠릅니다.
현재 도메인에 대해서만 쿠키를 추가 할 수 있습니다. Google 계정에 쿠키를 추가하려면
browser.get('http://google.com')
for cookie in cookies:
browser.add_cookie(cookie)
@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()
@Roel Van de Paar가 작성한 코드를 약간 수정 한 것입니다. 나는 이것을 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)
my os is Windows 10, and the chrome version is 75.0.3770.100. I have tried the 'user-data-dir' solution, didn't work. try the solution of @ Eric Klien fails too. finally, I make the chrome setting like the picture, it works!but it didn't work on windows server 2012.
setting
this is code I used in windows, It works.
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)
'program story' 카테고리의 다른 글
| 창 핸들이 만들어 질 때까지 컨트롤에서 Invoke 또는 BeginInvoke를 호출 할 수 없습니다. (0) | 2020.10.19 |
|---|---|
| UIButton에 그림자를 추가하는 방법은 무엇입니까? (0) | 2020.10.18 |
| Emacs 버퍼에서 단어의 모든 발생을 강조하는 방법은 무엇입니까? (0) | 2020.10.18 |
| XElement 또는 LINQ에서 XPath를 사용하는 방법은 무엇입니까? (0) | 2020.10.18 |
| Amazon S3 : 정적 웹 사이트 : 사용자 지정 도메인 또는 하위 도메인 (0) | 2020.10.18 |
