post 次尝试提交表单请求失败

Unsuccessful attempts to post request for form submission

我正在处理我的第一个项目,使用 python 提交表单并从 http://www.weather.gov

检索天气数据

我是 HTTP 表单提交的新手,因此我很可能做错了。我读过 mechanize and/or selenium 对于这类工作更有效,但我被学校的服务器限制为这些模块。

import requests

r = requests.get('http://www.weather.gov')

location = raw_input("Enter zipcode: ")
payload = {'key1' : location}

q = requests.post('http://forecast.weather.gov/', data = payload)

print q.text

我尝试搜索给定邮政编码的尝试没有成功,我没有到达给定邮政编码的当地天气。

注意:我也尝试过使用 urllib 和 urllib2 提交表单,但没有成功。

import urllib
import urllib2

location = raw_input("Enter Zip Code here: ")

url = 'http://forecast.weather.gov/'
values = {'inputstring' : location}
data = urllib.urlencode(values)

req = urllib2.Request(url, data = data)
response = urllib2.urlopen(req)

html = response.read()
print html

从检查页面看到的表单:

<form name="getForecast" id="getForecast" action="http://forecast.weather.gov/zipcity.php" method="get">
                <label for="inputstring">Local forecast by <br>"City, St" or ZIP code</label>
                <input id="inputstring" name="inputstring" type="text" value="Enter location ..." onclick="this.value=''" autocomplete="off">
                <input name="btnSearch" id="btnSearch" type="submit" value="Go">
                <div id="txtError">
                    <div id="errorNoResults" style="display:none;">Sorry, the location you searched for was not found. Please try another search.</div>
                    <div id="errorMultipleResults" style="display:none">Multiple locations were found. Please select one of the following:</div>
                    <div id="errorChoices" style="display:none"></div>
                    <input id="btnCloseError" type="button" value="Close" style="display:none">
                </div>
                <div id="txtHelp"><a style="text-decoration: underline;" href="javascript:void(window.open('http://weather.gov/ForecastSearchHelp.html','locsearchhelp','status=0,toolbar=0,location=0,menubar=0,directories=0,resizable=1,scrollbars=1,height=500,width=530').focus());">Location Help</a></div>
            </form>
<input id="inputstring" name="inputstring" type="text" value="Enter location    ..." onclick="this.value=''" autocomplete="off">

Post 到 URL http://forecast.weather.gov/zipcity.php 这就是 php 脚本用于从表单接收 post 数据的地方。