技術共有

ログインなしの Python Selenium 自動化 (Cookie とトークン)

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

目次

Cookieを使用しないログイン

インターフェイス経由で Cookie を取得する

ブラウザのバイパスログインを有効にする

トークンを追加


ログインを利用すると、毎回のログインの繰り返し操作を軽減したり、ログイン後のメニューページを直接操作したり、画像認証ログインなどのセキュリティ認証ログインの手間を軽減したりできます。注: Cookie とトークンには有効期限があります。

Cookieを使用しないログイン

開発者ツールから直接 Cookie を取得して追加します。下の図は、Web ページ上の複数のサイトの Cookie を示しています。必要なものを選択して追加します。

  1. from selenium import webdriver
  2. from selenium.webdriver.edge.options import Options
  3. # 一般只需要name和value
  4. cookie = {'name': 'ZY44', 'value': 'tLonhTkz50iHzxjhIsaaaafferr:C'}
  5. options = Options()
  6. # options.add_argument('--headless')
  7. wd = webdriver.Edge(options=options)
  8. wd.add_cookie(cookie_dict=cookie)
  9. #for c in cookies: # 如果是多个cookie要添加,cookies存储为列表是,使用循环添加
  10. # wd.add_cookie(c)
  11. wd.refresh() # 刷新页面
  12. wd.get(URL)
  13. wd.quit()

exception_class(メッセージ、画面、スタックトレース) を発生させます
selenium.common.exceptions.InvalidCookieDomainException: メッセージ: 無効な Cookie ドメイン
(セッション情報: MicrosoftEdge=126.0.2592.87)

上記のエラーが発生した場合は、次のように、wd.add_cookie(cookie_dict=cookie) の前に wd.get(URL) の行を追加できます。

  1. wd.get(URL)
  2. wd.add_cookie(cookie_dict=cookie)
  3. wd.get(URL)

インターフェイス経由で Cookie を取得する

インターフェイスを通じて Cookie データを取得した後、Selenium に Cookie の使用を追加します

  1. def get_cookies():
  2. headers = {
  3. 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36',
  4. }
  5. host = 'https://baike.baidu.com'
  6. req = requests.get(host, headers=headers)
  7. cookie_data = req.cookies.get_dict()
  8. cookies = []
  9. for key, value in cookie_data.items():
  10. cookies.append(dict(name=key, value=value))
  11. return cookies

ブラウザのバイパスログインを有効にする

Google またはエッジ ブラウザに次のように入力します。chrome://version/   或  edge://version/ 查看配置文件夹路径,最後に Default を削除し、パスの前に --user-data-dir= を追加して、必要なパスを結合します。

profile_directory = r'--user-data-dir=C:UsersxxxAppDataLocalMicrosoftEdgeUser Data'

  1. # 这里使用模糊匹配,把edge开头的进程都杀掉
  2. if platform.system() == "Windows":
  3. os.system("taskkill -im msedge* -f")
  4. else:
  5. os.system("killall -9 msedge*")
  6. user_data = r'C:UsersxxxAppDataLocalMicrosoftEdgeUser Data'
  7. profile_directory = rf'--user-data-dir={user_data}'
  8. options = Options()
  9. # options.add_argument('--headless')
  10. options.add_argument(profile_directory)
  11. wd = webdriver.Edge(options=options)
  12. wd.maximize_window()
  13. wd.get(URL)
  14. wd.quit()

注: この方法を使用する場合は、対応するブラウザ プログラムを閉じる必要があります。閉じるとエラーが報告されるため、実行前に対応するブラウザ プロセスを強制終了する必要があります。上記のコードはあいまい一致クエリを使用してプロセスを強制終了します。次のコードは完全一致です。

  1. returnCode=os.system('taskkill /F /iM chrome.exe') # 谷歌
  2. returnCode=os.system('taskkill /F /iM iexplore.exe') # IE
  3. returnCode=os.system('taskkill /F /iM firefox.exe') # 火狐
  4. returnCode=os.system('taskkill /F /iM msedge.exe') # edge
  5. assert returnCode==0 #判断浏览器进程是否杀完

トークンを追加

  1. token = "my_token"
  2. options = Options()
  3. options.add_argument('--headless')
  4. wd = webdriver.Edge(options=options)
  5. wd.execute_script("window.localStorage.setItem('token', '%s');" % token) # 使用selenium执行js的操作添加token
  6. wd.maximize_window()
  7. wd.get(url)
  8. wd.quit()