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

Posted

技术标签:

【中文标题】如何使用 Python 从 .aspx 页面检索数据?【英文标题】:How to retrieve data from .aspx page using Python? 【发布时间】:2019-12-24 05:54:13 【问题描述】:

我希望从 .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 的检查表明没有正确获取参数,因为仅显示输入查询之前的网页内容。

【问题讨论】:

您需要为此使用 selenium 或 scrapy 之类的东西 我开始使用 Selenium,但希望有更简单的方法!很高兴知道... 我在手机上看这个,所以请原谅我问:这应该是一个 POST 请求 requests.post(...) 吗? 【参考方案1】:

我发现 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.

【讨论】:

它没有使用beautifulsoup 来解析HTML,而是使用requests_html。 response.html.find 返回找到的元素列表,first=True 返回该列表中的第一项

以上是关于如何使用 Python 从 .aspx 页面检索数据?的主要内容,如果未能解决你的问题,请参考以下文章

从 ASP.NET SOAP 服务检索 XML 数据到 ASP.NET aspx 页面

如何从 aspx 中的 Gridview 行中检索主键以在 userControl.ascx 中使用?

从 ASP.NET 中的 POST 方法中检索数据

从 ASPX 站点使用 AJAX 检索 XML 数据

SQL 和 C# 从数据库中检索单个记录

如何从 API 发送 aspx 页面作为响应?