代码位置
https://github.com/duganlx/fopnp/tree/m/py3
获取经度与维度
文件位置:fopnp/py3/chapter01/search1.py
from geopy.geocoders import Nominatim
if __name__ == '__main__':
address = '207 N. Defiance St, Archbold, OH'
user_agent = 'Foundations of Python Network Programming example search1.py'
location = Nominatim(user_agent=user_agent).geocode(address)
print(location.latitude, location.longitude)
运行效果:
41.523569244186 -84.3062166453488
从谷歌地理编码API获取一个JSON文档
文件位置:fopnp/py3/chapter01/search2.py
import requests
def geocode(address):
base = 'https://nominatim.openstreetmap.org/search'
parameters = {'q': address, 'format': 'json'}
user_agent = 'Foundations of Python Network Programming example search2.py'
headers = {'User-Agent': user_agent}
response = requests.get(base, params=parameters, headers=headers)
reply = response.json()
print(reply[0]['lat'], reply[0]['lon'])
if __name__ == '__main__':
geocode('207 N. Defiance St, Archbold, OH')
运行效果
41.523569244186 -84.3062166453488
使用原始HTTP操作连接谷歌地图
文件位置:fopnp/py3/chapter01/search3.py
import http.client
import json
from urllib.parse import quote_plus
base = '/search'
def geocode(address):
path = '{}?q={}&format=json'.format(base, quote_plus(address))
user_agent = b'Foundations of Python Network Programming example search3.py'
headers = {b'User-Agent': user_agent}
connection = http.client.HTTPSConnection('nominatim.openstreetmap.org')
connection.request('GET', path, None, headers)
rawreply = connection.getresponse().read()
reply = json.loads(rawreply.decode('utf-8'))
print(reply[0]['lat'], reply[0]['lon'])
if __name__ == '__main__':
geocode('207 N. Defiance St, Archbold, OH')
运行效果
41.523569244186 -84.3062166453488
直接使用套接字与谷歌地图通信
文件位置:fopnp/py3/chapter01/search4.py
import socket
import ssl
from urllib.parse import quote_plus
request_text = """\
GET /search?q={}&format=json HTTP/1.1\r\n\
Host: nominatim.openstreetmap.org\r\n\
User-Agent: Foundations of Python Network Programming example search4.py\r\n\
Connection: close\r\n\
\r\n\
"""
def geocode(address):
unencrypted_sock = socket.socket()
unencrypted_sock.connect(('nominatim.openstreetmap.org', 443))
sock = ssl.wrap_socket(unencrypted_sock)
request = request_text.format(quote_plus(address))
sock.sendall(request.encode('ascii'))
raw_reply = b''
while True:
more = sock.recv(4096)
if not more:
break
raw_reply += more
print(raw_reply.decode('utf-8'))
if __name__ == '__main__':
geocode('207 N. Defiance St, Archbold, OH')
运行效果
HTTP/1.1 200 OK
Content-Type: application/json; charset=UTF-8
Date: Tue, 21 Oct 2014 22:50:21 GMT
Expires: Wed, 22 Oct 2014 22:50:21 GMT
Cache-Control: public, max-age=86400
Vary: Accept-Language
Access-Control-Allow-Origin: *
Server: mafe
X-XSS-Protection: 1; mode=block
X-Frame-Options: SAMEORIGIN
Alternate-Protocol: 80:quic,p=0.01
Connection: close
{
"results" : [
{
"address_components" : [
{
"long_name" : "207",
"short_name" : "207",
"types" : [ "street_number" ]
},
{
"long_name" : "North Defiance Street",
"short_name" : "N Defiance St",
"types" : [ "route" ]
},
{
"long_name" : "Archbold",
"short_name" : "Archbold",
"types" : [ "locality", "political" ]
},
{
"long_name" : "German",
"short_name" : "German",
"types" : [ "administrative_area_level_3", "political" ]
},
{
"long_name" : "Fulton County",
"short_name" : "Fulton County",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "Ohio",
"short_name" : "OH",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "United States",
"short_name" : "US",
"types" : [ "country", "political" ]
},
{
"long_name" : "43502",
"short_name" : "43502",
"types" : [ "postal_code" ]
}
],
"formatted_address" : "207 North Defiance Street, Archbold, OH 43502, USA",
"geometry" : {
"location" : {
"lat" : 41.521954,
"lng" : -84.306691
},
"location_type" : "ROOFTOP",
"viewport" : {
"northeast" : {
"lat" : 41.5233029802915,
"lng" : -84.3053420197085
},
"southwest" : {
"lat" : 41.5206050197085,
"lng" : -84.30803998029151
}
}
},
"types" : [ "street_address" ]
}
],
"status" : "OK"
}
解码输入字节,编码输出字符
文件位置:fopnp/py3/chapter01/stringcodes.py
if __name__ == '__main__':
# Translating from the outside world of bytes to Unicode characters.
input_bytes = b'\xff\xfe4\x001\x003\x00 \x00i\x00s\x00 \x00i\x00n\x00.\x00'
input_characters = input_bytes.decode('utf-16')
print(repr(input_characters))
# Translating characters back into bytes before sending them.
output_characters = 'We copy you down, Eagle.\n'
output_bytes = output_characters.encode('utf-8')
with open('eagle.txt', 'wb') as f:
f.write(output_bytes)
运行效果
'413 is in.'
将主机名转换为IP地址
import socket
if __name__ == '__main__':
hostname = 'www.baidu.com'
addr = socket.gethostbyname(hostname)
print('The IP address of {} is {}'.format(hostname, addr))
运行效果
The IP address of www.baidu.com is 163.177.151.110