2017-06-22 196 views
1

我正在學習如何登錄到網站pythonrequests,並通過YouTube上的各種不同的貼子和視頻在YouTube上的什麼是必需的,以及如何做到這一點。python請求登錄到網站

我發現當我點擊瀏覽器上的提交時,以下信息通過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

收集的所有內容,並在發出請求時使用此會話。 's.post'和's.get'而不是最後兩個請求 –

+0

謝謝@AndrewCherevatkin。你是對的。我應該使用's.post/s.get'而不是請求。這解決了我的問題。我很親密... –

回答

1

根據Andrew Cherevatkin所述,我應該使用s.posts.get而不是請求。通過使用requests.postrequests.get,我失去了通過session()