API爬取JSON
Urllib库的扩展
urllib除了最简单的read之外还有许多常见的函数,如读取服务器返回的各个信息:
from urllib import request
if __name__ == '__main__':
url = input('Please input the URL:') #http://fanyi.baidu.com
req = request.Request(url)
f = request.urlopen(req)
print('Status:',f.status,f.reason) #打印状态和原因
for k,v in f.getheaders(): #打印各个消息行的名称:内容
print('%s:%s'%(k,v))
print('*******************************')
print('geturl:%s'%(f.geturl())) #打印请求的服务器
print('*******************************')
print('getcode:%s'%f.getcode()) #打印状态码
Url加密用于get||post请求:
import urllib.request
from urllib import parse
url = "http://www.kiwisns.com/postLogin/"
values={'email':'xmj@user.com','password':'123456'}
data = urllib.parse.urlencode(values).encode()
geturl = url+'?'+str(data)
# get请求:
req_get = urllib.request.Request(geturl)
response1 = urllib.request.urlopen(req_get)
#post请求:
req_post = urllib.request.Request(url,data)
response2 = urllib.request.urlopen(req_post,data)
User-agent
有一些网站有防爬的测试,一般会通过user-agent来判断访问人员,但是python支持修改UA来达到绕过UA的目的,隐藏自己的身份。比如csdn就有反爬的设置,需要提交UA来爬取内容。
from urllib import request
if __name__ == "__main__":
url = input('please input URL:') #http://www.csdn.net/
head={}
head['User-Agent']='Mozilla/5.0 (Linux;Android 4.1.1; Nexus 7 Build/JRO03D)'
'AppleWebKit/535.19(KHTML, like Gecko) Chrome/18.0.1025.166 Safari/535.19'
req = request.Request(url,headers=head)
#req = request.Request(url)
response = request.urlopen(req)
html = response.read().decode('utf-8')
print(html)
Weather API
JSON(Object Notation, JS 对象简谱)是一种轻量级的数据交换格式。它基于ECMAScript(欧洲计算机协会制定的js规范)的一个子集,采用完全独立于编程语言的文本格式来存储和表示数据。简洁和清晰的层次结构使得 JSON 成为理想的数据交换语言。 易于人阅读和编写,同时也易于机器解析和生成,并有效地提升网络传输效率。作为前后端交流文件,它的格式设置尽可能的简化,我们可以通过json库来讲json文本与python文本进行转化,以下是构造get请求通过weather官网来获取各个城市天气情况的程序。
from tkinter import *
import urllib.request
import json
def ask(code):
url = 'http://www.weather.com.cn/data/cityinfo/%s.html'%code
obj=urllib.request.urlopen(url)
data_s=obj.read().decode('utf-8')
data_dict=json.loads(data_s)
rt=data_dict['weatherinfo']
my_rt = ('%s,%s,%s~%s')%(rt['city'],rt['weather'],rt['temp1'],rt['temp2'])
return my_rt
def fun_1(event):
code=Entry1.get()
info=ask(code)
Entry2.config(Entry2,text=info)
s.set("")
Entry2.insert(0,info)
def fun_2(event):
s.set("")
Entry2.insert(0,"")
if __name__ == "__main__":
root=Tk()
root.title('Weather Report')
root['width']=350; root['height']=130
Label(root,text="Choose the city:",width=15).place(x=1,y=1)
Entry1=Entry(root,width=30)
Entry1.place(x=110,y=1)
Label(root,text="Result:",width=18).place(x=1,y=20)
s=StringVar()
Entry2=Entry(root,width=30,textvariable=s)
Entry2.place(x=110,y=20)
Button1=Button(root,text='request',width=8)
Button1.place(x=40,y=80)
Button2=Button(root,text='clear',width=8)
Button2.place(x=200,y=80)
Button1.bind("<Button-1>",fun_1)
Button2.bind("<Button-1>",fun_2)
root.mainloop()