1.安装Requests && Lxml && bs4
pip install requests
pip install bs4
pip install lxml
2. requests简单应用
- 观察百度翻译是如何工作的
- 按照工作流程编写属于自己的翻译
- 翻译
import requests
import json
if __name__ == "__main__":
# 根据ajax的请求url,进行翻译
post_url = "https://fanyi.baidu.com/sug"
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36'
}
key = input("Input word:")
params = {
'kw':key
}
response = requests.post(url=post_url,data=params,headers=headers)
dic_obj = response.json()
fp = open('./translation.json','w',encoding='utf-8')
# json数据持久化存储
json.dump(dic_obj,fp=fp,ensure_ascii=False)
# 打印获取的json数据
print(dic_obj)
输出结果如下
Input word:python
{
'errno': 0, 'data': [{
'k': 'Python', 'v': '蛇属,蟒蛇属'}, {
'k': 'python', 'v': 'n. 巨蛇,大蟒'}, {
'k': 'pythons', 'v': 'n. 巨蛇,大蟒( python的名词复数 )'}]}
- KFC查询系统
post_url = 'http://www.kfc.com.cn/kfccda/ashx/GetStoreList.ashx?op=keyword'
cname = input("请输入城市:")
params = {
'cname': cname,
'pid':'',
'keyword': '',
'pageIndex': '1',
'pageSize': '10'
}
response = requests.post(url=post_url,params=params,headers=headers)
page_txt = response.text
filename = cname + '.html'
with open(filename , 'w' , encoding='utf-8') as fp:
fp.write(page_txt)
print(page_txt , 'OVER!')
输入城市地址就可以完成周边查询
请输入城市:北京
{
"Table":[{
"rowcount":443}],"Table1":[{
"rownum":1,"storeName":"前门","addressDetail":"西城区前门西大街正阳市场1号楼中部&