MIMEタイプがapplication/x-www-form-urlencoded
で、formパラメタでpostするものと思います。
Python, urllibを使ったログインがうまくいかない
解決したいこと
Python、urllibを使いソースコード内のサイトにログインし、ログイン後のhtmlを取得したいのですがどうしてもログインができず、ログイン画面のhtmlしか取得できません。
自分で思いつく限りの事は行ったのですが...どこに原因があるでしょうか?
該当するソースコード
import urllib.request
import json
URL = 'https://eowpf.alc.co.jp/login'
data = {
'username': 'emailaddress',
'password': 'password',
'login-form-type': 'pwd',
'checkbox': '1',
'login': 'ログイン'
}
headers = {'Content-Type': 'application/json'}
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor())
req = opener.open(urllib.request.Request(URL,json.dumps(data).encode(),headers))
res = req.read().decode()
print(res)
サイト側のhtml (細かいところは省略しています)
<form id="fmLogin" name="form1" method="post" onsubmit="javascript:return valCheck()" action="/login">
<input id="username" name="username" type="text" size="25" class="fInput">
<input id="password" name="password" type="password" size="25" class="fInput" autocomplete="off">
<input type="checkbox" name="checkbox" value="1">
<input type="hidden" name="login-form-type" value="pwd">
<input id="submit_button" name="login" type="submit" value="ログイン" class="submitbutt">
</form>
1Answer
Comments
@TakumiTheEarth
Questioner解決しました!一人では辿り着けませんでした、ありがとうございます。
@TakumiTheEarth
Questionerすみません、恥ずかしながら勘違いでした...。
やはりログイン前のhtmlが取得されてしまいます、他に考えられる原因はあるでしょうか?application/x-www-form-urlencodedでPOSTすることは間違いないと思います。
変更後のコードを見せてください。@TakumiTheEarth
Questionerありがとうございます、コードこちらです。
import urllib.request
import jsonURL = 'https://eowpf.alc.co.jp/login'
data = {
'username': 'xxx',
'password': 'xxx',
'login-form-type': 'pwd',
'checkbox': '1',
'login': 'ログイン'
}
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor())
req = opener.open(urllib.request.Request(URL,json.dumps(data).encode(),headers))
res = req.read().decode()
print(res)dataはjsonでなくformパラメタで指定する必要があります。
↓こんな感じかな?
res= opener.open(urllib.request.Request(URL, urllib.parse.urlencode(data), headers)) print(res)
@TakumiTheEarth
Questioner今度こそできました!お手数おかけしました、ありがとうございます。
import urllib.request import urllib.parse URL = 'https://eowpf.alc.co.jp/login' data = { 'username': 'xxx', 'password': 'xxx', 'login-form-type': 'pwd', 'checkbox': '1', 'login': 'ログイン' } headers = { 'Content-Type': 'application/x-www-form-urlencoded' } opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor()) req = opener.open(urllib.request.Request(URL,urllib.parse.urlencode(data).encode(),headers)) res = req.read().decode() print(res)
✌️
解決ならば、当Q&Aをクローズしてくださいね。
@TakumiTheEarth
Questioner感謝します!