質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

Q&A

解決済

1回答

803閲覧

【Python】APIのID連携のエラー対応

46bi_ru

総合スコア10

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

0グッド

0クリップ

投稿2022/05/22 07:47

解決したいこと:Yahoo!のAPIについて

初心者です。
pythonを利用して、ヤフーのID連携を行おうとしています。
ログイン画面までは到達したのですが、認可コードを取得するところで止まっています。

■やりたいこと
「Yahoo! ID連携に対応したAPIを利用したいため、認可コードを取得したい。」
流れとしては下記。
①クライアントIDとシークレットでauthorizationアクセス
②ログインして認可コードをもらう
③認可コードを使って、アクセストークンをもらう

発生している問題・エラー

認可コード s://auth.login.yahoo.co.jp/yconnect/v2/consent?session=lHGzBsWt&display=page&.scrumb=urAJ186NOzk&bcrumb=dD1oOWRpaUImc2s9TnluOFVXWmpIUVgzNWZVYTBRRG5DemZVeWtjLQ%3D%3D status:error 400

本来、「認可コード XXXXX」のように認可コードが取得できるのですが
エラーが発生しています。
原因を調べていたのですが、わからずご教示いただたいです。
Pythonに関しての知識はほとんどなく、調べながら行っています。
初歩的なことが原因かもしれませんが、どうぞよろしくお願いいたします。

ソースコード

Python

1 2import time 3import codecs 4import os 5import re 6 7import pandas as pd 8 9import requests, base64 10import xml.etree.ElementTree as ET 11from selenium import webdriver 12from webdriver_manager.chrome import ChromeDriverManager 13 14 15# Yahoo API 向け設定 16seller_id = "ストアのID" 17 18yid = "ヤフーのID" 19ypass = "ヤフーのパスワード" 20 21client_id = "発行したアプリケーションID" 22client_secret = "発行したシークレットID" 23 24redirect_uri = "https://shoppingXXXXXXXXXX" 25 26# YahooのAPIアクセストークンを取得する関数 27def Yahoo_get_token(): 28 29 url = "https://auth.login.yahoo.co.jp/yconnect/v2/authorization" 30 31 params = { 32 "response_type": "code", 33 "client_id": client_id, 34 "redirect_uri": redirect_uri, 35 "scope": "openid address profile email", 36 "bail": 1 37 } 38 39 res = requests.get(url, params=params) 40 time.sleep(1) 41 42 options = webdriver.ChromeOptions() 43 # options.add_argument('--headless') 44 driver = webdriver.Chrome(ChromeDriverManager( 45 log_level=0, print_first_line=False).install(), options=options) 46 driver.get(res.url) 47 time.sleep(1) 48 49 # ログイン処理 50 driver.find_element_by_name("login").send_keys(yid) 51 driver.find_element_by_name("btnNext").click() 52 time.sleep(1) 53 54 driver.find_element_by_name("passwd").send_keys(ypass) 55 driver.find_element_by_name("btnSubmit").click() 56 time.sleep(1) 57 58 # 認可コード 59 start = driver.current_url.find("code=") + 5 60 Length = len(driver.current_url) 61 code = driver.current_url[start:Length] 62 63 print("認可コード", code) 64 65 # selenium終了 66 driver.close() 67 driver.quit() 68 69 # アクセストークン 70 url = "https://auth.login.yahoo.co.jp/yconnect/v2/token" 71 72 data = { 73 "grant_type": "authorization_code", 74 "redirect_uri": redirect_uri, 75 "code": code, 76 } 77 78 base64_id_secret = client_id + ':' + client_secret 79 base64_id_secret_byte = base64.b64encode(base64_id_secret.encode('utf-8')) 80 auth_header = 'Basic ' + base64_id_secret_byte.decode('ascii') 81 82 headers = { 83 'HTTP-Version': 'HTTP/1.1', 84 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8', 85 'Authorization': auth_header 86 } 87 88 res = requests.post(url, data=data, headers=headers) 89 90 if res.status_code == 200: 91 res_json = res.json() 92 access_token = res_json["access_token"] 93 refresh_token = res_json["refresh_token"] 94 95 return res.status_code, [access_token, refresh_token] 96 else: 97 return res.status_code, [] 98 99# 指定された商品の商品情報を返します。 100# https://developer.yahoo.co.jp/webapi/shopping/getItem.html 101def API_item_get(token, item_code): 102 endpoint = "https://circus.shopping.yahooapis.jp/ShoppingWebService/V1/getItem" 103 104 params = { 105 'seller_id': seller_id, 106 'item_code': item_code 107 } 108 109 headers = { 110 'HTTP-Version': 'HTTP/1.1', 111 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8', 112 'Authorization': 'Bearer ' + token, 113 } 114 115 res = requests.get(endpoint, params=params, headers=headers) 116 xml = res.text 117 return xml 118 119def API_item_category(token): 120 endpoint = "https://circus.shopping.yahooapis.jp/ShoppingWebService/V1/stCategoryList" 121 122 params = { 123 'seller_id' : seller_id, 124 # "page_key": page_key 125 } 126 127 headers = { 128 'HTTP-Version': 'HTTP/1.1', 129 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8', 130 'Authorization': 'Bearer ' + token, 131 } 132 133 res = requests.get(endpoint, params=params, headers=headers) 134 xml = res.text 135 136 return xml 137 138def save_csv(df, dir_path, filename): 139 os.makedirs(dir_path, exist_ok=True) 140 with codecs.open(os.path.join(dir_path, filename), 'w', 'shift_jisx0213', 'ignore') as f: 141 df.to_csv(f, index=False) 142 143def xml2df(xml_data): 144 root = ET.XML(xml_data) # element tree 145 all_records = [] 146 for i, child in enumerate(root): 147 record = {} 148 for subchild in child: 149 record[subchild.tag] = subchild.text 150 all_records.append(record) 151 df = pd.DataFrame(all_records) 152 return df 153 154def test(): 155 # Yahoo APIアクセストークン取得 156 status, token = Yahoo_get_token() 157 158 # 正常に取得できた場合以下実行 159 if status == 200: 160 xml = API_item_category(token[0]) 161 df = xml2df(xml) 162 163 save_csv(df, "./", "output.csv") 164 else: 165 print("status:error", status) 166test()

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

melian

2022/05/22 08:20

params = { "response_type": "code", "client_id": client_id, "redirect_uri": redirect_uri, "scope": "openid address profile email", "bail": 1 } res = requests.get(url, params=params) の直後に、 print(res.headers['Location']) を入れて実行すると何が表示されますか?
46bi_ru

2022/05/22 09:03

ご回答いただきありがとうございます! 下記が表示されました。 Traceback (most recent call last): File "XX.py", line 189, in <module> test() File "XX.py", line 176, in test status, token = Yahoo_get_token() File "XX.py", line 46, in Yahoo_get_token print(res.headers['Location']) File "C:\ファイルのパス.....\structures.py", line 54, in __getitem__ return self._store[key.lower()][1] KeyError: 'location'
guest

回答1

0

自己解決

下記記述の前に「time.sleep(20)」を追加することで解決しました。

python

1driver.close() 2driver.quit()

投稿2022/05/26 23:14

46bi_ru

総合スコア10

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問