Skip to main content
 首页 » 编程设计

python之如何使用 Python 从 .aspx 页面检索数据

2024年11月01日17webabcd

我希望从 .aspx 网站访问数据,该网站包含许多需要输入参数的字段。数据将在 Pandas 中进一步分析。我显然在这里遗漏了一些步骤,因此我们将不胜感激。网址是https://www.cocorahs.org/ViewData/StationPrecipSummary.aspx

我正在尝试一种使用 Python 库 Requests 的简单方法,获取 json,然后转换为 DataFrame。

parameters = {'Station 1':'MD-BL-13','Start Date':'8/01/2019','End Date':'08/10/2017'} 
response = requests.get('https://www.cocorahs.org/ViewData/StationPrecipSummary.aspx', params=parameters) 
data = response.json() 
pd.read_json(data) 

我想获得一个包含“日期”列和“Precip mm”列的 DataFrame,其中包含请求时间段的数据。检查 response.content 表明参数没有正确获取,因为只显示输入查询之前的网页内容。

请您参考如下方法:

我发现 ASP.NET 网站处理起来很麻烦,但这里有一个使用 pandas 和 requests-html 的解决方案。

from requests_html import HTMLSession 
import pandas as pd 
 
 
with HTMLSession() as s: 
 
    r = s.get('https://www.cocorahs.org/ViewData/StationPrecipSummary.aspx') 
    hiddens = r.html.find('input[name=__VIEWSTATE]', first=True).attrs.get('value') 
 
    payload = { 
        '__EVENTTARGET': '', 
        '_VIEWSTATE': hiddens, 
        'obsSwitcher:ddlObsUnits': 'usunits', 
        'tbStation1': 'MD-BL-13', 
        'ucDateRangeFilter:dcStartDate': '8/1/2019', 
        'ucDateRangeFilter_dcStartDate_p': '2019-8-1-0-0-0-0', 
        'ucDateRangeFilter:dcEndDate': '8/10/2019', 
        'ucDateRangeFilter_dcEndDate_p': '2019-8-10-0-0-0-0', 
        'btnSubmit': 'Get Summary' 
        } 
 
 
    r = s.post('https://www.cocorahs.org/ViewData/StationPrecipSummary.aspx', data=payload) 
    table = r.html.find('table.Grid', first=True) 
    df = pd.read_html(table.html, header=0)[0] 
    print(df) 
 
 
          Date Precip in. 
0   08/01/2019       0.00 
1   08/02/2019       0.00 
2   08/03/2019       0.00 
3   08/04/2019       0.00 
4   08/05/2019       0.00 
5   08/06/2019       0.00 
6   08/07/2019          T 
7   08/08/2019       1.73 
8   08/09/2019         -- 
9   08/10/2019         -- 
10    Totals :   1.73 in.