【问题标题】:Unsuccessful attempts to post request for form submission未成功尝试发布表单提交请求
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

    • 谢谢佐罗!我的代码的 urllib 版本可以正常运行。尽管如此,仍然无法让请求版本正常工作。感谢您的回答!
    • 那是因为您的请求版本中传递的字段是错误的。使用“输入字符串”而不是“输入邮政编码”
    猜你喜欢
    • 1970-01-01
    • 2010-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多