2017-06-22 147 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()