2017-06-22 7 views
1

私はpythonrequestsでウェブサイトにログインする方法を学び、必要なものとそれを行う方法について、stackoverflowとvideos on youtubeのさまざまな投稿を行ってきました。python requestウェブサイトへのログイン

ブラウザでsubmit(送信)をクリックすると、以下の情報がformに送信されていることが判明しました。 私は唯一のネットワークの下で開発ツールに行って、私はそれがログインページ自体にある私が言うことができる何

を伝えることができますどのようなヘッダ

form response when submitting on website

で見ていた、彼らusernamepasswordのうち、次のコードがhtmlのものであることを尋ねます。

<div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓"><input name="authenticity_token" type="hidden" value="T8NxfsxCHqUPzdvmM++VIpipimDyjsLHkg4Oz3Yuouk="></div> 
<ul class="sic_loginFailed"> 
    <li> 
     <label for="sic_login_header_username">Username</label> 
     <input id="sic_login_header_username" name="name" type="text" class="sic_formText"> 
    </li> 
    <li> 
     <label for="sic_login_header_password">Password</label> 
     <input id="sic_login_header_password" name="password" type="password" class="sic_formText"> 
    </li> 
    <li class="sic_remember"> 
     <input id="sic_login_header_remember" name="remember" type="checkbox"> 
     <label for="sic_login_header_remember">Remember my login.</label> 
    </li> 
    <li> 
     <input type="hidden" name="redirect" 
value="https://www.shareinvestor.com/sg"> 



     <input id="sic_login_submit" type="submit" value="Sign In" class="sic_greenInputButton"> 
    </li> 
    </ul> 

はだからauthenticity tokenpassword_mは、ウェブサイトによって自動生成されていることを意味しますか?注:私は自分のアカウントを作成したときにpassword_mが私に割り当てられていると感じています。しかし、トークンはすべてのログイン時に自動的に生成されます。

私の質問は、私が研究している私が知っていると何に基づいて、以下のコードを書いたが、私はまだウェブサイトにログインすることができません。

url = "https://www.shareinvestor.com/user/login.html" # This is the main URL login page 

login_data = {'name': 'test_user', 
       'password': 'test_password', 
       'password_m': '5d93ceb70e2bf5daa84ec3d0cd2c731a', 
       'remember': True, 
       'redirect': 'https://www.shareinvestor.com/sg'} 

with requests.Session() as s: 
    a = s.get(url).text 
    b = bs4.BeautifulSoup(a, 'lxml') 
    c = b.findAll('input', type='hidden') # This is to draw out the token. I tried searching for it in the cookies previously, but failed badly.... 
    for i in c: 
     login_data[i['name']] = i['value'] 

    # I use the this url for the response because as per the `Headers` in the picture above, it says that this is the request URL that the form is submitting to. 
    response = requests.post('https://www.shareinvestor.com/user/do_login.html?use_https=1', data=login_data) 
    response = requests.get('https://www.shareinvestor.com/user/edit_profile.html', cookies=response.cookies) 

    print(response.text) 

あなたがここまで読んだことがあるならば、私は本当にあなたが私がウェブサイトにログインしようとする際に正しいか間違ってやっているものにいくつかの光を当てることができれば感謝し、ログインを持続します。

+1

リクエスト中にセッションを使用します。最後の2つのリクエストではなく 's.post'と' s.get'です –

+0

ありがとう@AndrewCherevatkin。あなたが正しいです。リクエストの代わりに 's.post/s.get'を使うべきです。これは私の問題を解決します。私はとても近かった... –

答えて

1

Andrew Cherevatkinの言葉通り、私はs.posts.getを要求の代わりに使用しなければなりません。 requests.postrequests.getを使用すると、私が収集したすべてが失われます。session()

関連する問題