1
我正在学习如何登录到网站python
和requests
,并通过YouTube上的各种不同的贴子和视频在YouTube上的什么是必需的,以及如何做到这一点。python请求登录到网站
我发现当我点击浏览器上的提交时,以下信息通过form
发送。 我去下网络开发工具和拍了一下头
我可以告诉
我可以告诉的是,在登录页面本身,他们只要求提供username
和password
,其中以下代码为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 token
和password_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)
如果你已经读到这里,我真的很感激,如果你能摆脱对我做的对还是错在试图登录到网站上的一些光,并持续登录。
收集的所有内容,并在发出请求时使用此会话。 's.post'和's.get'而不是最后两个请求 –
谢谢@AndrewCherevatkin。你是对的。我应该使用's.post/s.get'而不是请求。这解决了我的问题。我很亲密... –