将信息从html传递给python

2024-04-19 15:56:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我对python和html非常陌生,我一直在尝试使用python(使用cgi)运行simplehttpserver。从这个服务器上我可以运行位置.py显示用户地理位置的文件。我想把这个位置写进电脑的文本文件里,但我不知道怎么做。目前我的位置.py实际上是一个由python加载的html5页面,但我不知道如何从我的页面中提取所需的信息。在

另外,我的灵感是让我的iphone和我的笔记本电脑共享同一个wifi网络(adhoc便携式热点),然后让我的笔记本在googleearth中使用iphone更精确的gps。我最终想写进一个kml文件,这个文件会随着我当前的lat和long不断更新。可能有更简单的方法来实现这一点,但我认为学习一点python是个好主意。在

我的位置.py文件

#!/python

print( "Content-type: text/html\n\n")
print( """\
<html>
<head>

<p id="demo">Test:</p>
<script>
var x=document.getElementById("demo");
function getLocation()
  {
  if (navigator.geolocation)
    {
    navigator.geolocation.getCurrentPosition(showPosition);
    }
  else{x.innerHTML="Geolocation is not supported by this browser.";}
  }
function showPosition(position)
  {
  x.innerHTML="Latitude: " + position.coords.latitude + 
  "<br>Longitude: " + position.coords.longitude;
  }
  window.onload = getLocation;
</script>
</head>
<body>
</body>
</html>""")

和我的服务器文件(网络服务器.py)在

^{pr2}$

Tags: 文件py网络服务器navigatordemohtmlscript
1条回答
网友
1楼 · 发布于 2024-04-19 15:56:15

您需要向服务器发送一个包含位置的请求,然后在脚本中使用cgi.FielStorage来获取数据。要发送请求,您必须稍微修改一下javascipt代码。在

我向您展示了一个发送静态数据的示例(因为我的Pc上没有地理位置:p),您需要更改它以发送正确的lat,lon数据(可能在函数showPosition内?)在

接下来,对python脚本进行更改(请检查javascript上是否也有更改!)公司名称:

#!/usr/bin/env python

import cgi

form = cgi.FieldStorage()

lat = form.getvalue('lat')
lon = form.getvalue('lon')

with open('location.txt','wt') as f:
    if lat:
        f.write(lat)
    f.write("\n")
    if lon:
        f.write(lon)

f.close()

print( "Content-type: text/html\n\n")
print( """\
<html>
<head>

<p id="demo">Test:</p>
<script>
var x=document.getElementById("demo");
function getLocation()
  {
  //this is to send the location back to your python script
  var req = new XMLHttpRequest();
  req.open('GET', 'location.py?lat=1&lon=2', false);
  req.send(null);    
  //                           

  if (navigator.geolocation)
    {
    navigator.geolocation.getCurrentPosition(showPosition);
    }
  else{x.innerHTML="Geolocation is not supported by this browser.";}
  }
function showPosition(position)
  {
  x.innerHTML="Latitude: " + position.coords.latitude + 
  "<br>Longitude: " + position.coords.longitude;
  }
  window.onload = getLocation;
</script>
</head>
<body>
</body>
</html>""") 

如果您运行代码,您将在文件位置.txt你有坐标。在

当然,您可以将流程拆分为两个脚本(几乎可以肯定是正确的方法!)并将请求发送到第二个脚本(保存_位置.py也许吧。在

相关问题 更多 >