import requests
import json
if name=='main':
#指定url
url='http://www.kfc.com.cn/kfccda/ashx/GetStoreList.ashx?op=keyword'
#UA伪装
headers={'User-Agent':' Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36 SLBrowser/7.0.0.12151 SLBChan/30'}
word=input("enter a word:")
data={'cname':'', 'pid':'', 'keyword': word,'pageIndex':' 1','pageSize': '10'}
response = requests.post(url=url,data=data,headers=headers)
page_text=response.text
data_json = json.loads(page_text)
#print(data_json)
filename=word+".json"
fp=open(filename,'w',encoding='utf-8')
json.dump(data_json,fp=fp,ensure_ascii=False)
print("over!")
D:\python\Python38\python.exe D:/pythonProject3/肯德基位置信息.py
enter a word:北京
Traceback (most recent call last):
File "D:/pythonProject3/肯德基位置信息.py", line 10, in
response = requests.post(url=url,data=data,headers=headers)
File "D:\python\Python38\lib\site-packages\requests\api.py", line 117, in post
return request('post', url, data=data, json=json, **kwargs)
File "D:\python\Python38\lib\site-packages\requests\api.py", line 61, in request
return session.request(method=method, url=url, **kwargs)
File "D:\python\Python38\lib\site-packages\requests\sessions.py", line 515, in request
prep = self.prepare_request(req)
File "D:\python\Python38\lib\site-packages\requests\sessions.py", line 443, in prepare_request
p.prepare(
File "D:\python\Python38\lib\site-packages\requests\models.py", line 319, in prepare
self.prepare_headers(headers)
File "D:\python\Python38\lib\site-packages\requests\models.py", line 453, in prepare_headers
check_header_validity(header)
File "D:\python\Python38\lib\site-packages\requests\utils.py", line 1025, in check_header_validity
raise InvalidHeader("Invalid return character or leading space in header: %s" % name)
requests.exceptions.InvalidHeader: Invalid return character or leading space in header: User-Agent
Process finished with exit code 1