-
讲解内容:requests 库的基础使用、实例
-
引入requests库
-
调用get方法,需要传入请求的url地址
-
输出响应内容(可以获取服务器返回的http头部信息,http响应内容,响应码等)
-
第二个方法为实例内容(可以获取对应地址的经纬度)
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# requests 库的基本使用
import requests #引入requests库
url="https://www.baidu.com"
def getMethod(url):
html=requests.get(url) #通过get方法发送请求到指定的url
print(html.status_code) #获取响应码
print(html.encoding) #默认编码 ISO-8859-1
html.encoding='utf-8' #设置新的编码,避免输出乱码
print(html.text) #输出服务器返回的内容
print(html.headers) #打印http头部信息
print(html.headers['Server']) #获取指定http头部字段,不区分大小写
print(html.headers['server']) #获取指定http头部字段,不区分大小写
pass
# 获取地址对应经纬度
def getLocation():
address="上海市东方明珠"
url="https://apis.map.qq.com/ws/geocoder/v1/?address={}&key=H3IBZ-IHNWI-I55G4-5XHG3-LKKDO-TUFUX".format(address)
html=requests.get(url)
print(html.status_code)
print(html.text)
pass
if __name__ == '__main__':
getMethod(url)
print("""+++++++++++++++++++++++"""*5)
getLocation()
实例结果运行