AJax的post请求和get请求:
1.浏览记录的不同
(i)get会有浏览记录,例如会记录账号,密码。
(ii)post请求不会有浏览记录。
2.发送请求的方法不同
(i)post是将参数以具体内容发送给服务器。
(ii)get是将参数拼接到url后面进行传递。
3.服务器获取参数的方法不同
(i)使用post请求时,服务器端使用Request.Form来获取参数
(ii)使用get请求时,服务器端使用Request.QueryString来获取参数
post和get方法使用不同情景:
post一般用于数据的添加,post可以避免url过长。
get 用于内容的搜索,查找表单资源。
post请求:
def create_request(page):
bases_url='http://www.kfc.com.cn/kfccda/ashx/GetStoreList.ashx?op=cname'
data={
'cname':'北京',
'pid':'',
'pageIndex':page,
'pageSize':'10'
}
data=urllib.parse.urlencode(data).encode('utf-8')
headers={'User-Agent':'Mozilla/5.0(Windows NT 10.0;Win64; x64)AppleWebKit/537.36(KHTML,like Gecko)Chrome/106.0.0.0 Safari/537.36'}
url=bases_url+str(data)
request=urllib.request.Request(url=url,headers=headers,data=data)
return request
def get_content(request):
response=urllib.request.urlopen(request)
content=response.read().decode('utf-8')
return content
def down_load(page,content):
with open('kfc'+str(page)+'.json','w',encoding='utf-8') as fp:
fp.write(content)
# 程序的入口
if __name__ == '__main__':
start_page = int(input("起始页面:"))
end_page = int(input("结束页面:"))
for page in range(start_page, end_page + 1):
request = create_request(page)
content = get_content(request)
down_load(page,content)
get请求:
def creat_request(page):
url = 'https://movie.douban.com/top250?start={a}&filter='.format(a=page * 25)
headers = {
'User - Agent': 'Mozilla / 5.0(Windows NT 10.0;Win64;x64) AppleWebKit / 537.36(KHTML, likeGecko) Chrome / 106.0..0Safari / 537.36Edg / 106.0.1370.37'}
# 请求对象的定制
request = urllib.request.Request(url=url, headers=headers)
# 返回request
return request
# 获取响应的数据
def get_content(request):
response = urllib.request.urlopen(request)
content = response.read().decode('utf-8')
return content
# 下载
def down_load(page, content):
with open('douban' + str(page) + '.json', 'w', encoding='utf-8')as fp:
fp.write(content)
# 程序的入口
if __name__ == '__main__':
start_page = int(input("起始页面:"))
end_page = int(input("结束页面:"))
for page in range(start_page, end_page + 1):
request = creat_request(page)
content = get_content(request)
down_load(page, content)