【发布时间】:2016-07-30 04:47:41
【问题描述】:
我正在开发我的第一个项目,使用 python 提交表单并从http://www.weather.gov检索天气数据
我是 HTTP 表单提交的新手,因此我很可能会搞错这一切。我读过 mechanize 和/或 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">
【问题讨论】:
标签: python forms python-requests urllib2 urllib