ajax的post请求
import urllib.request
import urllib.parse
# url = 'https://www.kfc.com.cn/kfccda/ashx/GetStoreList.ashx?op=cname'
#
# headers = {
# 'user-agent':"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36"
# }
#定制请求
def create_request(page):
url = 'https://www.kfc.com.cn/kfccda/ashx/GetStoreList.ashx?op=cname'
headers = {
'user-agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36"
}
data = {
'cname': "北京",
'pid': '',
'pageIndex': page,
'pageSize': 10
}
new_data = urllib.parse.urlencode(data).encode('utf-8')
request = urllib.request.Request(url=url,data=new_data,headers=headers)
return request
def get_response(request_data):
reponse = urllib.request.urlopen(request_data)
context = reponse.read().decode('utf-8')
return context
def download(page,context):
with open('kfc'+ str(page) + '.json','w',encoding='utf-8') as pf:
pf.write(context)
if __name__ == '__main__':
start_page = int(input('请输入起始页码'))
end_page = int(input('请输入结束页码'))
page: int
for page in range(start_page,end_page+1):
# 定制请求
request_data = create_request(page)
# 获取响应数据
context = get_response(request_data)
# 下载数据
download(page,context)
标签:__,python,基础,request,urllib,context,data,page
From: https://www.cnblogs.com/dhcc/p/18295886