Python 中的 CGI 脚本用于搜索数据库并打印结果
我想编写一个 CGI 脚本,它采用表单数据,将其发送到搜索引擎,进行搜索,然后在运行我的 CGI 脚本的网页上显示结果。我一直在尝试使用 urllib 和 urllib2。
在我的脚本中: hello.py
if form.has_key("data_search"):
datasearch = form["data_search"].value
url = 'http://www.example.com/'
data = urlparse.urlparse(datasearch)
data2 = urllib.urlencode(data)
req = urllib2.Request(url, data2)
response = urllib2.urlopen(url, data2)
the_page = response.read()
print response
response.close()
所以我想获取用户输入(datasearch),将其发送到不同网址(www.example.com)的搜索引擎,并在我的网页(www .server.com/cgi-bin/hello.py)。
当前的脚本不起作用。我不确定我刚刚犯了某种语法错误,或者我是否需要完全新的方法。
第一个错误位于
data2 = urllib.urlencode(data)
内置 TypeError = 类型错误:不是有效的非字符串序列或映射对象 args = ('不是有效的非字符串序列或映射对象',)
其中 '打印数据' 的结果是 ('', '', 'TTBar', '', '', '') 并且 TTBar 是我的询问。
I would like to write a CGI script that takes the form data, sends it to a search engine, searches, then displays the results on the webpage where my cgi script it run. I have been trying to use urllib and urllib2.
In my script: hello.py
if form.has_key("data_search"):
datasearch = form["data_search"].value
url = 'http://www.example.com/'
data = urlparse.urlparse(datasearch)
data2 = urllib.urlencode(data)
req = urllib2.Request(url, data2)
response = urllib2.urlopen(url, data2)
the_page = response.read()
print response
response.close()
So I would like to take the user input (datasearch), send it to a search engine at a different url (www.example.com), and print the results of the search on my webpage (www.server.com/cgi-bin/hello.py).
This current script is not working. I am not sure I have just made some sort of syntax error or if I need a new approach entirely.
The first error is in
data2 = urllib.urlencode(data)
builtin TypeError =
TypeError: not a valid non-string sequence or mapping object
args = ('not a valid non-string sequence or mapping object',)
where the result of 'print data' is ('', '', 'TTBar', '', '', '') and TTBar is my query.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不确定您如何获取表单数据,但
datasearch = form["data_search"].value
似乎已返回data_search
参数的值。使用 urlparse.urlparse 解析完整的 url,即 http://somesite.com /?datasearch=TTBAR。因此,考虑到这一点,您可以这样做:或者更好地使用优秀的 requests 库:
Not sure how you are getting your form data, but it appears that
datasearch = form["data_search"].value
returns the value of yourdata_search
param already. Useurlparse.urlparse
to parse a full url, i.e., http://somesite.com/?datasearch=TTBAR. So with that in mind you can do this:Or even better use the excellent requests library: