通过POST使用请求库进行python身份验证

时间:2016-06-14 15:42:46

标签: python http-post python-requests forms-authentication

我读了几个类似的主题..我试着跟随其他的例子,但我仍然陷入了无处不在的境地.. 我有python编程的基本技能和关于http协议的一点知识,我的两个目标是: - 通过请求库对网站进行身份验证 - 在会话激活时登录后从网站获取数据

这是代码:

import requests

targetws = 'https://secure.advfn.com/login/secure'

s = requests.session()

payload_data = {'login_username': 'xxx', 'login_password': 'yyy'}

response = s.post(targetws, data=payload_data)


url='https://it.advfn.com/mercati/BIT/generali-G/ordini'

result = s.get(url) 

print result.content

但我登录时总是没有成功.. 也许我错过了提交动作等帖子数据的某些价值? 任何帮助将不胜感激,最好的问候!

这里是页面中的html代码:

form action="https://secure.advfn.com/login/secure" id="login_form" name="login_form" method="POST" target="">

        <input type="hidden" value="aHR0cDovL2l0LmFkdmZuLmNvbQ==" name="redirect_url" id="redirect_url">
        <input type="hidden" value="it" name="site" id="site">

        <div class="fields"><label for="login_username">Username</label> 
            <input type="text" tabindex="1" class="text ui-widget-content" value =""
            id="login_username" name="login_username" maxlength="64">
        </div>

        <div class="fields"><label for="login_password">Password</label> 
            <input tabindex="2" type="password" class="text ui-widget-content" value="" id="login_password" name="login_password" maxlength="16">
        </div>
                <div class="fields">
                    <strong><a href="/common/account/password/request">Se ti sei dimenticato la tua password</a></strong> &nbsp;
                    <input  class="button"  tabindex="3" type="submit"   value="Accedi" id="login_submit">
                </div>
    </form 

1 个答案:

答案 0 :(得分:1)

如果你看一下发布的内容:

enter image description here

您认为自己需要redirect_urlsite,您可以使用bs4从源代码中的输入进行解析:

import requests
from bs4 import BeautifulSoup

data = {"redirect_url": "",
        "site": "uk",
        "login_username": "foo",
        "login_password": "bar"}

with requests.Session() as s:
    log = "https://secure.advfn.com/login/secure"
    r = s.get("http://uk.advfn.com/")
    soup = BeautifulSoup(r.content)
    redirect_url = soup.select_one("#redirect_url")["value"]
    site =  soup.select_one("#site")["value"]
    data["redirect_url"] = redirect_url
    p = s.post(log, data=data)
    print(p.content)
    print(s.get('https://it.advfn.com/mercati/BIT/generali-G/ordini').content)

一旦这样做,您将成功登录。