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

Login to a website with a radio button using python's request module

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

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.
我是从站点解析数据的新手,因此真诚欢迎任何意见,在此先感谢。

P.S。名字r"Login1$RadioButtonList_Type"指的是那个网站上的单选按钮的名字,我想把它的值设为Tuna.

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

# -*- 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