python - 使用python的请求模块通过单选按钮登录网站

标签 python python-2.7 post python-requests basic-authentication

我正在尝试登录一个网站并在其中检索一些日期。我尝试了以下代码:

from requests import session  

payload = {  
    r"Login1$UserName": "myusername",  
    r"Login1$Password": "thepassword",  
    r"Login1$RadioButtonList_Type": "Tuna"  
}  

with session() as s:
    s.post("http://elogbook.ofdc.org.tw/", data=payload)
    req = s.get("http://elogbook.ofdc.org.tw/Member/CatchReportTuna.aspx")
    print(req.text)

但是结果显示我没有登录该站点。我想知道为什么上面的代码失败了,以及如何登录 the website .
我是从站点解析数据的新手,因此真诚欢迎任何意见,在此先感谢。

附言名称 r"Login1$RadioButtonList_Type" 指的是该网站上单选按钮的名称,我想将其值设置为 Tuna

最佳答案

关键问题是隐藏的 ASP.NET 表单字段也应该是负载的一部分。这意味着您首先需要向页面发出 GET 请求并解析隐藏的 input 字段值。此外,您需要提供一个 User-Agent header 。使用 BeautifulSoup对于 html 解析部分:

# -*- coding: utf-8 -*-
from bs4 import BeautifulSoup
from requests import session

payload = {  
    r"Login1$UserName": "myusername",  
    r"Login1$Password": "thepassword",  
    r"Login1$RadioButtonList_Type": "Tuna",
    r"Login1$LoginButton": u"登入"
}  
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.111 Safari/537.36'}

with session() as s:
    s.headers = headers
    response = s.get('http://elogbook.ofdc.org.tw/')

    soup = BeautifulSoup(response.content)

    for input_name in ['__EVENTTARGET', '__EVENTARGUMENT', '__VIEWSTATE', '__VIEWSTATEGENERATOR', '__EVENTVALIDATION']:
        payload[input_name] = soup.find('input', {'name': input_name}).get('value', '')

    s.post("http://elogbook.ofdc.org.tw/", data=payload)

    req = s.get("http://elogbook.ofdc.org.tw/Member/CatchReportTuna.aspx")
    print(req.content)

仅供引用,您还可以使用以下工具提交表单而不必担心隐藏的表单字段:


另一种选择是通过 selenium 自动化一个真实的浏览器来模仿真实的你。 :

from selenium import webdriver

login = "mylogin"
password = "mypassword"

driver = webdriver.Firefox()
driver.get('http://elogbook.ofdc.org.tw/')

# fill the form
driver.find_element_by_id('Login1_UserName').send_keys(login)
driver.find_element_by_id('Login1_Password').send_keys(password)
driver.find_element_by_id('Login1_RadioButtonList_Type_0').click()

# submit
driver.find_element_by_id('Login1_LoginButton').click()

driver.get('http://elogbook.ofdc.org.tw/Member/CatchReportTuna.aspx')
print driver.page_source

关于python - 使用python的请求模块通过单选按钮登录网站,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28623889/

相关文章:

android - 如何在 JAVA/Android 中使用 Woocommerce REST API 的 'POST' Http Verb?

python - 请帮助我理解 Python 中的类

python - 仅在Windows中的两个文件夹之间获取大小写不匹配的文件名

php - 从 PHP 执行 Python - 选择 Python 版本 (Linux - CentOS)

python - 类型错误 : unsupported operand type(s) for -: 'str' and 'int' (Python)

objective-c - Restkit Post总是会出现故障

python - Keras:如何加载具有两个输出和自定义损失函数的模型?

python - 从项目中 Grep 类/函数

python - 将输出序列化为 JSON - ValueError : Circular reference detected

php - 如何将值 POST 到两个不同的 PHP 页面