【问题标题】:Adding query parameters to a URL将查询参数添加到 URL
【发布时间】:2019-05-30 14:11:26
【问题描述】:

我正在尝试从网站自动下载数据。我需要将动态参数传递给每天都在变化的站点。 html 的结构是表格而不是表格。如何传递我的参数并从 url 获取结果?

这是我尝试过的,它需要在 python 2.7 中

import urllib

url = "https://disc.gsfc.nasa.gov/SSW/#keywords="

params = urllib.urlencode({'keyword':"(GPM_3IMERGHHE)", 't1':"2019-01-02", 't2':"2019-01-03", 'bboxBbox':"3.52,32.34,16.88,42.89"})
r = urllib.urlopen(url, params)

return = r.read()

【问题讨论】:

    标签: python python-2.7 url web-scraping urllib


    【解决方案1】:

    您需要将查询参数附加到基本 url,以便urllib.urlopen 创建一个 GET 请求。

    >>> url = "https://disc.gsfc.nasa.gov/SSW/#keywords="
    
    >>> params = {'keyword':"(GPM_3IMERGHHE)", 't1':"2019-01-02", 't2':"2019-01-03", 'bboxBbox':"3.52,32.34,16.88,42.89"}
    >>> quoted_params = urllib.urlencode(params)
    >>> quoted_params
    'bboxBbox=3.52%2C32.34%2C16.88%2C42.89&t2=2019-01-03&keyword=%28GPM_3IMERGHHE%29&t1=2019-01-02'
    
    >>> full_url = url + quoted_params
    >>> full_url
    'https://disc.gsfc.nasa.gov/SSW/#keywords=bboxBbox=3.52%2C32.34%2C16.88%2C42.89&t2=2019-01-03&keyword=%28GPM_3IMERGHHE%29&t1=2019-01-02'
    
    >>> resp = urllib.urlopen(full_url)
    >>> html = resp.read()
    

    【讨论】:

    • 谢谢你。我能够完成这项工作,但现在在 IronPython 2.7.7 中实现它时遇到了不同的挑战。请在下面查看我的答案,如果您能提供帮助,请告诉我。 T
    【解决方案2】:

    我能够在 Python 2.7 中完成这项工作,如下所示,但由于软件依赖性,我需要在 IronPython 2.7.7 中实现这一点。我收到一条错误消息,提示“未知 url 类型:https”我了解 IronPython 2.7.9 之前的版本存在 https 问题。有没有办法绕过安全检查?

    >>> import urllib
    >>> url_keys = urllib.urlencode( {'action': "SUBSET", 'no_attr_prefix': 1, 'content_key_is_value': 1, 'force_array': 1,
    ...         'pretty': 0, 'start': "2019-01-02T00:00:00Z", 'end': "2019-01-04T23:59:59Z", 'south': 0.28,
    ...         'west': 32.77, 'north': 13.64, 'east': 44.72, 'variables': "precipitationCal", 'format': "netCDF",
    ...         'dataset_id': "GPM Level 3 IMERG Early Half Hourly 0.1 x 0.1 degree Precipitation V05", 'agent_id': "OPeNDAP"})
    >>> url = "https://disc.gsfc.nasa.gov/daac-bin/SSW/SSW"
    >>> r = urllib.urlopen(url, url_keys)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-28
      • 1970-01-01
      • 2019-09-20
      • 1970-01-01
      • 2016-08-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多